Aside from the vast number of pointless comparisons you're making, the first problem is that you're ignoring the result of Stream.Read
... and instead creating a string out of the whole 1024 bytes within message
. If you change it to:
int bytesRead = stream.Read(message, 0, message.Length);
string messageIn = Encoding.ASCII.GetString(message, 0, bytesRead);
... then you'd be in a much better position. However, that's probably still not good enough, unless that's all that's going to be sent. You're dealing with a stream, but I suspect you're thinking about it as if it's message-oriented - as if a single Write
on one end of the connection will map to a single Read
on the other end. That's not how stream-oriented protocols work. If you have a logical "message" then when reading from the stream you might end up with part of a message, multiple messages, anything. Common ways of fixing this are:
- Include a length prefix before each message
- Use a separator (e.g. a line break for text-based protocols)
See Marc Gravell's blog post on this for more details.
Additionally, if your protocol is text-based, it would be a good idea to create a StreamReader
around the stream so that you can just read text (e.g. a line at a time) instead of converting all over the place.