开发者

C# stream out of order when using TCP send/receive

开发者 https://www.devze.com 2023-02-27 07:58 出处:网络
I was creating a small client/server application when I encountered something that seemed to be a mixup in the TCP streem, so I wrote a small test application

I was creating a small client/server application when I encountered something that seemed to be a mixup in the TCP streem, so I wrote a small test application

The server just creates a TCP socket and sends an incrementing counter

IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, 7777);
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(ipEndPoint);
socket.Listen(10);

Socket clientSocket = socket.Accept();

byte test = 0;
while (true)
{
    if (clientSocket.Send(new byte[] { test }, 0, 1, SocketFlags.None) == 1)
    {
 开发者_StackOverflow社区       test++;
    }
}

As this is a TCP stream I would expect a stream at the client that just goes from 0 to 255 and so on.

Using the following at the client:

IPEndPoint ipEndPoint = new IPEndPoint(System.Net.IPAddress.Parse("127.0.0.1"), 7777);
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(ipEndPoint);

byte[] buffer = new byte[20000];
byte last = 255;
while (true)
{
    int bytesRead = socket.Receive(buffer);

    for (int i = 0; i < bytesRead; i++)
    {
        if (buffer[i] != (byte)(last+1))
        {
            //problem here
        }
        last = buffer[i];
    }
}

The if condition should never return true but it does. After I analyzed the stream at the client it showed that quite often the buffer contains sequences like 000 001 002 003 004 005 006 102 103 104 105.

What am I missing here? I always thought TCP would ensure in order delivery at the TCP level.

Update: Thorarin pointed to the correct solution. Zone Alarm was messing around with the stream (or probably with the packets). I am going to uninstall this software.


TCP does guarantee in order delivery. My guess would be something is going wrong with your receive buffer. Maybe you are connecting twice and using the same buffer?

I've tried to reproduce your problem, but I cannot. I'm not sure what clientSocketState is referring to, so I used a regular byte array for the buffer. Instead of BeginAccept I lazily used Accept, but no other changes were made.

Something else must be going on that you're not telling us :-)

Update: considering everything, I'm starting to believe that some firewall or anti-virus software is messing things up for you.

0

精彩评论

暂无评论...
验证码 换一张
取 消