C#TCP服务器模拟

C#TCP服务器模拟,c#,sockets,tcp,server,client,C#,Sockets,Tcp,Server,Client,我有一个随时可用的应用程序(客户端),它通过TCP连接到服务器,我使用Wireshark查看发生了什么,得到了以下结果: 客户端将此数据包发送到服务器: |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|6

我有一个随时可用的应用程序(客户端),它通过TCP连接到服务器,我使用Wireshark查看发生了什么,得到了以下结果:

客户端将此数据包发送到服务器:

|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.

任何想法都很好,谢谢

我建议
TcpClient client=server.AcceptTcpClient();
NetworkStream=client.GetStream();
在while循环中。 创建一个新线程,以便在接收消息时不阻塞ui

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知道流何时结束,因此您不必给出
Bytes.Length
,也不必在每条消息之后关闭流。 您的错误通常在服务器或客户端崩溃时出现,或者在TcpListener或TcpClient上调用了
.Close()

希望这对您有所帮助。

找到了一些相关信息:,但不确定它是否对您有帮助。您如何判断何时收到来自服务器的所有数据?在发送任何数据之前,必须等待所有数据被接收,并且TCP数据可能会以多条消息的形式出现。GetStream()方法正在阻止一个在流/连接关闭之前不会返回的。因此,如果您随后发送数据,您将收到一个错误,因为连接已关闭。