2016-01-23 124 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()时,通常会出现错误。 希望这可以帮助你。