Sending variable-length data over a TCP socket

My application should send / receive xml data via tcp socket. It is not possible to include any fixed-length header containing the length of the message. As far as I understand, data transmitted through tcp can go to the receiver like this.

  • <Messa

  • GE> <contents

  • > Hello </ content>

  • </ message>

But one way or another, this does not mean that data sent with one Send () operation (assuming that it is shorter or equal to the size of the socket buffer) is always read completely with one Receive () operation. Is the scenario described above possible, given that the endpoint socket buffers are large enough and never exceeded?

+3
source share
3 answers

This can easily happen if a proxy exists between them. If we assume that the proxy does not exist, the client will receive the same packets as the server. If you send data in parts less than the TCP MSS of your link, the client will probably receive it in one piece.

However, I would not rely on this. It's easy to tell the end of an XML message by seeing the close ( </message>) tag , so it's easy to parse XML from a stream.

+1
source

Yes it is possible.

You really cannot assume that the buffer boundaries in the send () operation on one side will coincide with those seen by the corresponding recv () on the other end, even if this happens in most cases.

, , , TCP, . , , , ...

+4

You can specify the length of the message in your messages. All you have to do is send the xml msg message, adding it with a length of msg in the first 4 bytes, and then in xml msg. When you receive, you take the first 4 bytes of the stream as the length of msg and then read each byte for xml msg

0
source

Source: https://habr.com/ru/post/1763647/


All Articles