TCP read and write from client and server

后端 未结 3 1560
夕颜
夕颜 2021-01-29 13:16

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

3条回答
  •  生来不讨喜
    2021-01-29 13:54

    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:

    1. Read the length of the message (the amount of bytes)
    2. Store the length in an Integer.
    3. Choose a header (usually a one-byte header is enough).
    4. Concatenate the length with the header, and then that with the rest of the message.

    This will produce the following structure:

    [Length (4 bytes)][Header (1 byte)][Message (?? byte(s))]
    

    To read it:

    1. Read the first 4 bytes, and convert the returned array to an Integer.
    2. Read the next byte to get the header.
    3. Read until you've read the whole length of the message. Determine what you'll do with the message based on the header.

    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!

提交回复
热议问题