New to TCP socket communications in C#, having a problem where I send some data across the network stream from my client app, then read it from my server app. Data comes through fine the first time, but the next time I try to send data, the old data is still in the network stream and just gets overridden up to whatever the length of the new data is. This is causing issues when trying to parse the data in the stream. I have tried adding a null termination but it doesn’t seem to have any effect.
How can I empty the network stream before sending more data across?
We send a string such as this:
1|0|bob|cornell|9/14/2012 12:49:34 AM
Then another one like this:
1|0|jim|horne|9/14/2012 12:49:34 AM
But the second string goes through as :
1|0|jim|horne|9/14/2012 12:49:34 AMAM
…followed by a bunch of \0.
The last chunk is a DateTime, and it is failing to convert the string to a DateTime because of the extra AM. Even when appending \0 to the end of the string we are sending across the stream, it won’t work. For example:
1|0|jim|horne|9/14/2012 12:49:34 AM\0M
It seems to treat the null termination as just another character, rather than a signal to stop reading the string.
It seems that “Flush” does nothing on NetworkStream types. Must be a dumb problem here, but any help is appreciated.
The client does this:
private static void writeToServer(MessagePacket message, NetworkStream clientStream)
{
clientStream.Write(message.ToBytes(), 0, message.ToBytes().Length);
}
The server does this:
byte[] rawMessage = new byte[4096];
while (true)
{
try
{
clientStream.Read(rawMessage, 0, 4096);
clientStream.Flush();
}
catch
{
break;
}
newPacket = new MessagePacket(rawMessage);
}
Stream.Read() returns the number of received bytes, the bytes after after that are undefined.