2012-09-18 49 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,每當我想讓服務器發送消息時提供客戶端的套接字。