I\'m trying to make a client and server which can read and write info back and forth between each other. I can write from the client and server reads it but not vise versa and I
The problem why your client never receives the response is due to that you never let it.
You never initialize the client's Receiver
stream, the application isn't breaking because A) the error is thrown in a different thread, B) you just break the while
loop when the error occurs, you really need to log the error somehow.
Use only one NetworkStream
. The stream supports simultaneous receiving and sending, and it's much easier having one than two - you will not forget to initialize it as easily.
In the future you should also look into handling your messages. As TCP is stream based, you can get messages in any possible way; one third of a message, half a message, or just one byte at a time (etc.). There are a few ways to solve this, but the best method is length-prefixing (or length prefixing).
Length-prefixing combined with header-prefixing makes your messages as reliable as they get when it comes to receiving them properly. If done correctly you can always be sure that you get a message containing the correct, and correct amount of data.
Length- and header-prefixing means that you prefix each message with it's correct length, and a header telling what the message is for. This is how it's composed:
This will produce the following structure:
[Length (4 bytes)][Header (1 byte)][Message (?? byte(s))]
To read it:
Reading that sequence you will always know how much to read and expect from the other endpoint, and thus you won't have a problem with partial or messages being lumped together.
Hope this helps!