0

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

(我已经对代码段进行了编号以发现程序的流程)

一切顺利,直到服务器发回确认。当代码在客户端 (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.
4

1 回答 1

0

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

于 2012-09-25T06:09:51.013 回答