I'm making a client-server app in .NET, but now I got the problem that I try to send something, the client is reading it and while reading I'm sending something else so it makes crap of the sent data开发者_运维技巧.
Example:
- I send test
- Client starts reading
- I send endtest
- Client reads test@$>@est
Is there a way to solve this? Now I'm doing a Thread.Sleep(10)
after a send but I think there is a better way :P.
P.S. I'm using NetworkStream.Write()/Read()
, not NetworkStream.BeginWrite()/BeginRead()
. Which of these two is better and why?
The problem may be that you are using the same socket to send multiple "things" of data. You may know that you have sent a string and then an image, but, TCP doesn't see separate objects, only a single stream of bytes.
You also cannot know how many read calls you'll need to make to get your "first" data object. To delineate multiple objects is outside the scope of TCP. The point being, this problem is best solved by using one single socket per transaction. Create a socket, write your entire data to it in a single write call, then close the socket. Have the client read until you have the entirety of the data. If you need to send something else, make a new socket.
I know this isn't specific to the NetworkStream class, but I hope it helps.
you should look into using WCF with nettcpbinding for this sort of stuff especially if both ends (client / server) are in C#.
I previously had similar problems writing custom tcp code but moved over to wcf and its significantly easier, and more stable so you can just focus on writing your application code.
If I were you I would create a rule, when sending and receiving data. As to say you have a starting char like $ for example and * is the ending char. That will help your client/server system to know when to read or when to write, and eventually avoid garbage in the process. so in terms of steps:
- Client sends message $hello world*
- Server starts to read when it sees the $ and stops after the *
then again, maybe a code example of what you are doing could help us pinpoint exactly what you are doing wrong.
精彩评论