Asynchronous TCP socket bytes merging

后端 未结 2 382
清歌不尽
清歌不尽 2020-12-22 10:20

I wasn\'t quite sure how to explain my problem in the title, but I\'ll try to elaborate on my problem.

Basically I\'m coding a chat that is not P2P, but where all us

相关标签:
2条回答
  • 2020-12-22 10:47

    That's why they call it a stream. You put bytes in at one end and TCP guarantees they come out in the same order, none missing or duplicated, at the far end. Anything bigger than a byte is your problem.

    You have to accumulate enough bytes in a buffer to have your header. Then interpret it and start processing additional bytes. You may have a few left over that start the next header.

    This is normal behavior. When your application is not receiving data the system will be buffering it for you. It will try to hand off the available data the next time you make a request. On the other side, a large write may travel over connections that do not support an adequate frame size. They will be split as needed and arrive eventually in dribs and drabs.

    0 讨论(0)
  • 2020-12-22 10:52

    This usually happens when two or more packets of data are sent at close intervals. I recently had this problem myself, and the way I resolved it was to a separating key. You can then tokenize each message. For example, you could add the ASCII character #4 (the End-of-Transmission character) to the end of each message being sent like I did.

    Write("Message1" + ((char)4).ToString())
    Write("Message2" + ((char)4).ToString())
    

    Then, when the client receives the data, you can iterate through the received data. When it finds that special character, it knows it's the end of one message, and (maybe) the beginning of a new one.

    "Message1(EOT char)Message2(EOT char)"
    

    \n may be easier to work with than using ASCII characters.

    0 讨论(0)
提交回复
热议问题