2016-01-23 128 views
2

我有現成的使用的應用程序(客戶端),它連接到通過TCP服務器,我使用Wireshark的,看看發生了什麼,得到了這一點:C#TCP服務器仿真

客戶端向服務器發送該包:

|00|18|e7|96|92|13|fc|f8|ae|2b|7a|4b|08|00|45|00|00|3f|6d|d8|00|00|80|11|49|7d|c0|a8|01|07|c0|a8|01|01|c2|b3|00|35|00|2b|cc|7f|5e|fe|01|00|00|01|00|00|00|00|00|00|05|70|61|6e|65|6c|07|6d|75|66|69|62|6f|74|03|6e|65|74|00|00|01|00|01| 

和服務器回答回來:

0xfc 0xf8 0xae 0x2b 0x7a 0x4b 0x00 0x18 0xe7 0x96 0x92 0x13 0x08 0x00 0x45 0x28 0x00 0x34 0x00 0x00 0x40 0x00 0x34 0x06 0x2a 0xa4 0x95 0xca 0xc4 0x7e 0xc0 0xa8 0x01 0x07 0x19 0x9b 0xde 0x39 0x18 0x24 0xd5 0x66 0x85 0xa3 0xb1 0x7b 0x80 0x12 0x72 0x10 0xc4 0x81 0x00 0x00 0x02 0x04 0x05 0xac 0x01 0x01 0x04 0x02 0x01 0x03 0x03 0x07 

所以我當前服務器的代碼是:

Int32 port = 6555; 
IPAddress localAddr = IPAddress.Parse("127.0.0.1"); 
var g1 = new byte[] { 0xfc, 0xf8, 0xae, 0x2b, 0x7a, 0x4b, 0x00, 0x18, 0xe7, 0x96, 0x92, 0x13, 0x08, 0x00, 0x45, 0x28, 0x00, 0x34, 0x00, 0x00, 0x40, 0x00, 0x34, 0x06, 0x2a, 0xa4, 0x95, 0xca, 0xc4, 0x7e, 0xc0, 0xa8, 0x01, 0x07, 0x19, 0x9b, 0xde, 0x39, 0x18, 0x24, 0xd5, 0x66, 0x85, 0xa3, 0xb1, 0x7b, 0x80, 0x12, 0x72, 0x10, 0xc4, 0x81, 0x00, 0x00, 0x02, 0x04, 0x05, 0xac, 0x01, 0x01, 0x04, 0x02, 0x01, 0x03, 0x03, 0x07 }; 

server = new TcpListener(localAddr, port); 
server.start(); 
while(true) 
{ 
    TcpClient client = server.AcceptTcpClient(); 
    NetworkStream stream = client.GetStream(); 
    while ((i = stream.Read(bytes, 0, bytes.Length)) != 0) 
    { 
      stream.Write(g1, 0, g1.Length); 
    } 
} 
stream.close(); 
} 

所以只要服務器從客戶端接收的東西,它必須將G1字節(它只是用於測試目的),但我得到這個錯誤的客戶端連接到服務器後:

Unable to read data from the transport connection: An established connection was aborted by the software in your host machine. 

任何想法會很好,謝謝

+0

找到一些相關信息:http://stackoverflow.com/questions/14304658/c-sharp-an-established-connection-was-aborted-by-the-software-in-your-host-machi,不確定如果它會幫助你。 –

+0

如何知道何時從服務器接收到所有數據?在發送任何數據之前,您必須等待,直到接收到所有數據,並且TCP數據可能包含多條消息。 GetStream()方法阻塞直到流/連接關閉纔會返回。因此,如果您發送數據,則會因連接關閉而發生錯誤。 – jdweng

回答

0

我建議TcpClient client = server.AcceptTcpClient(); NetworkStream stream = client.GetStream(); 裏面的while循環。 用於在接收消息

private void GetMessageThread() 
    { 
     bool receive = true; 
     Stream strm = client.GetStream(); 
     while (receive) 
     { 
      try 
      { 
       IFormatter formatter = new BinaryFormatter(); 
       string obj; 
       if (strm.CanRead) 
       { 
        obj = (string)formatter.Deserialize(strm); 
       } 
       else 
       { 
        _receive = false; 
        break; 
       } 
      } 
     } 
    } 

在這種情況下,BinaryFormatter的知道什麼時候有流的末尾不會阻塞UI創建一個新的線程,所以你不必給Bytes.Length,你不必關閉每條消息之後的流。 當服務器或客戶端崩潰或在TcpListener或TcpClient上調用.Close()時,通常會出現錯誤。 希望這可以幫助你。