2012-09-18 16 views
0

我正在开发基于Windows的聊天应用程序。当客户端首次发送Command类时,服务器会处理它并通过发送另一个Command类来确认客户端。试图反序列化对象时程序挂起

(I有编号的代码段至斑点程序的流程)

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

嗨,不知道这是问题所在,但是当您通过发送和接收数据时,您必须关闭NetworkStream。关闭TcpClient不会释放NetworkStream。 – Cybermaxs

+0

@Cyber​​maxs感谢您的评论,但什么“当你通过发送”意味着?每次发送命令后,我是否必须关闭NetworkStream? – manas

+1

你能清楚地陈述你的问题吗? –

回答

0

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