这个小项目背后的想法是开发一个聊天应用程序,区别在于我想发送对象而不是纯粹的字符串。到目前为止,这就是我所拥有的。内存异常与BeginRead
如果我反序列化构造函数,它工作得很好(UserDTO目前只有2个字符串字段),但是,我打算让多个客户端随时随地将数据发送到服务器。即使在阅读MS的文档之后,我也很难理解它是如何工作的以及如何解决错误(就像这样,它给出了一个“异常类型'System.OutOfMemoryException'被抛出。”)像你们的一些想法。
注意给谁试图编译这个:BinaryFormatter的在做这个作为一个办法:让我们说UserDTO具有的属性字符串名称,字符串电子邮件 运用这一类的客户端和服务器,你必须使用一个类来构建它库,并将这个引用添加到这两个项目中,因为不知怎的,binaryformater说甚至是如果你在两个项目中创建相同的类,反序列化声明它不能映射对象。我将留下下面我使用的客户端示例。
服务器:
class Program {
const int serverPort = 60967;
static List<UserConnection> clientList = new List<UserConnection>();
static TcpListener listener;
static Thread listenerThread;
static void Main(string[] args) {
listenerThread = new Thread(new ThreadStart(DoListen));
listenerThread.Start();
Console.WriteLine("Server Started");
//while (true) {
string a = Console.ReadLine()
//}
}
static void DoListen() {
try {
listener = new TcpListener(System.Net.IPAddress.Any, serverPort);
listener.Start();
Console.WriteLine("Listening [...]");
do {
UserConnection client = new UserConnection(listener.AcceptTcpClient());
//clientList.Add(client);
Console.WriteLine("New connection found");
} while (true);
}
catch (Exception ex) {
Console.WriteLine(ex.ToString());
}
}
}
public class UserConnection {
private TcpClient clientInfo;
private byte[] readBuffer = new byte[2000];
const int READ_BUFFER_SIZE = 2000;
public UserConnection(TcpClient client) {
clientInfo = client;
clientInfo.GetStream().BeginRead(readBuffer, 0, READ_BUFFER_SIZE, new AsyncCallback(StreamReceiver), null);
}
private void StreamReceiver(IAsyncResult ar) {
try
{
if (client.GetStream().CanRead) {
lock (clientInfo.GetStream()) {
var strm = clientInfo.GetStream();
int BytesRead = clientInfo.GetStream().EndRead(ar);
BinaryFormatter formatter = new BinaryFormatter();
var mydat = (UserDTO)formatter.Deserialize(strm);
}
lock (clientInfo.GetStream()) {
clientInfo.GetStream().BeginRead(readBuffer, 0, READ_BUFFER_SIZE, new AsyncCallback(StreamReceiver), null);
}
}
catch (Exception e) {
Console.WriteLine(ex.ToString());
}
}
客户:
class Program {
static void Main(string[] args) {
ConnectResult("localhost", 60967);
Console.ReadLine();
}
}
static string ConnectResult(string ip, int port) {
try {
TcpClient client = new TcpClient(ip, port);
AttemptLogin(client);
return "Connection Succeeded";
}
catch (Exception ex) {
return "Server is not active. Please start server and try again. " + ex.ToString();
}
}
static void AttemptLogin(TcpClient client) {
UserDTO obj = new UserDTO("email", "username");
IFormatter formatter = new BinaryFormatter();
var stream = client.GetStream();
formatter.Serialize(stream, obj);
Console.WriteLine("Sent Object");
}
}
何时'while(true);'循环退出? (回答:当程序内存耗尽时,我假设) – Quantic
仅用于测试目的,它现在从不退出,主要是反序列化部分给我一个很难的时间(当使用字符串和Streamwriter时,它适用于多个客户端) – abr
@Quantic我怀疑这是问题,因为循环没有增加正在使用的内存量。 – EJoshuaS