C# 尝试反序列化对象时,程序挂起
我正在开发一个基于windows的聊天应用程序。当客户机第一次发送命令类时,服务器获取并处理该命令类,并通过发送另一个命令类来确认客户机 (我对代码段进行了编号,以确定程序的流程) 一切顺利,直到服务器发回确认。当代码在客户端(5.)中运行以反序列化并获取确认的副本时,客户端程序将失去响应。但是服务器(6)中的代码似乎在工作——它成功地序列化了命令 有人能指出这里出了什么问题吗 提前谢谢 服务器代码:C# 尝试反序列化对象时,程序挂起,c#,sockets,deserialization,networkstream,binaryformatter,C#,Sockets,Deserialization,Networkstream,Binaryformatter,我正在开发一个基于windows的聊天应用程序。当客户机第一次发送命令类时,服务器获取并处理该命令类,并通过发送另一个命令类来确认客户机 (我对代码段进行了编号,以确定程序的流程) 一切顺利,直到服务器发回确认。当代码在客户端(5.)中运行以反序列化并获取确认的副本时,客户端程序将失去响应。但是服务器(6)中的代码似乎在工作——它成功地序列化了命令 有人能指出这里出了什么问题吗 提前谢谢 服务器代码: //1. Server runs first try { BinaryFormatte
//1. Server runs first
try
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
//2. Server is blocked here waiting for an incoming stream
Command newCommand = (Command)binaryFormatter.Deserialize(networkStream);
}
catch (Exception ex)
{
MessageBox.Show("EXCEPTION: " + ex.Message);
Console.WriteLine(ex.Message);
}
Client c = new Client(newCommand.ClientName, endPoint,
clientServiceThread, client);
// ...processing the newCommand object
Command command = new Command(CommandType.LIST);
try
{
TcpClient newTcpClient = new TcpClient(newClient.Sock.RemoteEndPoint
as IPEndPoint);
newTcpClient.Connect(newClient.Sock.RemoteEndPoint as IPEndPoint);
NetworkStream newNetworkStream = newTcpClient.GetStream();
BinaryFormatter binaryFormatter = new BinaryFormatter();
//6. Server serializes an instance of the Command class to be recieved by the client
binaryFormatter.Serialize(newNetworkStream, command);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
Console.WriteLine(ex.Message);
newClient.Sock.Close();
newClient.CLThread.Abort();
}
客户端代码:
//3. Client runs second
TcpClient tcpClient = new TcpClient('localhost', 7777);
NetworkStream networkStream = tcpClient.GetStream();
Command newCommand = new Command(CommandType.CONN);
try
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
//4. Client serializes an instance of a Command class to the NetworkStream
binaryFormatter.Serialize(networkStream, newCommand);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
BinaryFormatter binaryFormatter = new BinaryFormatter();
//5. Then client is blocked until recieve an instance of command class to deserialize
Command serverResponse = (Command)binaryFormatter.Deserialize(networkStream);
clientForm.updateChatMessages(serverResponse);
//7. Instead of recieving the instance of the Command class, the clients go unresponsive
// and the client program hangs.
我想出来了。由于服务器正在为多个客户端提供服务,因此我犯了一个错误,即从同一个
NetworkStream
实例反序列化。因此,我更改了代码以创建一个新的网络流
,每次我希望服务器发送消息时都提供客户端的套接字。您好,不确定这是问题所在,但在发送和接收数据时必须关闭网络流。关闭TcpClient不会释放NetworkStream。@Cybermaxs感谢您的评论,但“当您通过发送”是什么意思?我是否每次发送命令后都必须关闭NetworkStream?你能清楚地说明你的问题吗?@Y.ecari为了清晰起见,我编辑了原始帖子。请让我知道任何进一步的澄清。谢谢