问题
I am trying to implement a Client/Server model using TCpClient
, with its Networkstream.Write()/Read()
functions sending/receiving a byte array.
It works most the time, except if I try to send three or more byte arrays in a row right after one another. The client says it sends them all, but the server only receives the first two.
Below is the code I use to write from client to server.
byte[] buffer = p.toByteArray(level);
stream.Write(buffer, 0, buffer.Length);
stream.Flush();
Is it consolidating them or something? I just don't understand how the server can receive distinct arrays when I send 2, but not 3 or more. If I separate the 3 writes, it works OK, but I really don't want to do that.
Any help would be much appreciated.
EDIT:
SOLVED :) Thanks for all your guys help. It was pushing 2-3 packets at a time, and my system was thinking 1 burst = 1 packet. I just rewrote my existing architecture with TCPClient to detect multiple packets :) Again, thanks for the help!
回答1:
There is one very important core rule that is important to account for when you do Sockets programming:
It is not guaranteed that whatever client sent in X writes, server will receive exactly in the same amount of reads. It can be one write on client and 10 reads on server. It can be 10 writes and client and just one read on server.
Let's say the client sends 3 messages, 100 bytes each. Server might receive 150 bytes and then another 150 bytes. Or 100 bytes and 200 bytes.
The only thing that is guaranteed if you work with TCP is that the order will be preserved, in other words that whatever you sent first will arrive first on the server.
You can use one of the following basic techniques to separate the data:
- markers (some kind of byte sequence that delimit messages)
- constant length per message
- length in the message header
- combination of the above
来源:https://stackoverflow.com/questions/6325676/having-trouble-sending-three-or-more-packets-consecutively