尝试反序列化对象时程序挂起

时间:2012-09-18 07:25:29

标签: c# sockets deserialization networkstream binaryformatter

我正在开发基于Windows的聊天应用程序。当客户端首先发送Command类时,服务器会让它处理它并通过发送另一个Command类来确认客户端。

(我已编号代码段以发现程序的流程)

一切顺利,直到服务器发回确认。当代码在客户端(5.)中运行以反序列化并获取确认的副本时,客户端程序将无响应。但是服务器(6.)中的代码似乎正常工作 - 它成功地序列化了命令。

有人能指出这里有什么不对吗?

提前致谢。

服务器代码:

//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.

1 个答案:

答案 0 :(得分:0)

我明白了。由于服务器为多个客户端提供服务,因此我错误地从同一个NetworkStream实例反序列化。因此,每当我希望服务器发送消息时,我通过提供客户端套接字来更改代码以创建新的NetworkStream