I have the following code to read messages sent from a server to the client:
while (true) {
byte[] readBuffer = new byte[327680];
StringBuilder message = new StringBuilder(327680);
while (true) {
do {
int bytes = ServerStream.Read(readBuffer, 0, readBuffer.Length);
message.AppendFormat("{0}", Encoding.ASCII.GetString(readBuffer, 0, bytes));
}
while (ServerStream.DataAvailable);
if (message.Length > 0) {
foreach (string msg in message.ToString().Split(MESSAGE_END)) {
if (msg != "") ProcessServerMessage(msg);
}
message.Clear();
readBuffer = new byte[327680];
}
}
}
Unfortunately… Every now and then the variable ‘message’ appears to chop off, for no reason I can understand. I’ve made the read buffer huge, to see if that was the issue, but it doesn’t help. It seems to happen when the server sends lots of data at once, but nowhere near 327680 bytes…
Also, when checking the server logs, it appears to be sending the data completely, un-chopped. It’s like half the info is ‘lost’ on the internet somewhere… But this is TCP, so that shouldn’t happen, right?
Thanks in advance
It’s not lost, you’re not doing buffered reading correctly. Even though you’re checking
DataAvailable, odds are that the sender hasn’t flushed that data yet. So it’s “on the way” (waiting to be sent), butDataAvailablewill return false because it hasn’t yet arrived.It’s always better to send an integer ahead of the data so that the receiver knows how much data to expect, OR to look for some kind of terminator (null, newline, something).