Agge B
Agge B

Reputation: 45

send message speed socket

I have been working on a project where I send strings from a client to a server in C#. My questions are the following, if some of you have the time to answer:

where clientStream is a NetworkStream. But it becomes a problem if the functions are in a while loop as following:

while(true)
{
        clientStream.Write(buffer, 0, buffer.Length);
        clientStream.Flush();
}

The messages seems to sometimes be intertwined and corrupt at the server part. But not if I add a Thread.Sleep (with perhaps 30 as an in parameter) call in the while loop. I wonder why the messages gets intertwined if it's an TCP socket connection? How does the function calls:

clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();

work?

Upvotes: 1

Views: 677

Answers (1)

nyxthulhu
nyxthulhu

Reputation: 9752

Don't flush your client stream always, you only want to flush at the end of your write cycle otherwise let .NET take care of it for you. Flushing every time you send something is inefficient.

Also remember that TCP streams can arrive in a different order and are re-assembled on the recipient side to make sense using TCP Serials, this is done transparently but if your looking at the streams via wireshark then you may be seeing this.

In theory you can send as much data through a socket as your bandwidth supports. But you should never reply on Thread.Sleeps as this will blow up on you one day. Relying on timing for ANYTHING like this is considered a "dirty hack" and will cause issues.

Upvotes: 1

Related Questions