Arza
Arza

Reputation: 27

I need to receive two packets separately - linux combines them as one and sends to the application

My device is connected to a TCP server, which send a heartbeat at regular intervals. At times this heart beat packets arrives along with some other packet and in the program where I am reading on a socket, these two packets get combined and read as a single packet which causes application issues with application logic. It is still possible for me to add some workaround, but is there any way to tell the kernel to send these two packets as separate packets and not as a single?

Logic on the server - accepts incoming connections, when a device connects, creates a separate thread to talk to the device, TCP_NODELAY is set, I am using poll before reading the data from the socket. There are about 100 threads at any given point in time.

Upvotes: 1

Views: 343

Answers (1)

John Kugelman
John Kugelman

Reputation: 362197

TCP is a streaming protocol. You should not rely on packet boundaries to detect message boundaries. Packets can be combined and split apart at any point by either machine's OS, NICs, or intermediate routers. Do not expect that every write() system call will have a corresponding read().

Similarly, you must not rely on packets being received whole. You must handle the possibility of partial reads. You can get partial packets from read() calls at any time.

It is standard practice to implement message framing at the application level: prefix each message with a header that includes a length and perhaps also message ID. Read the length and then read that many bytes. If you don't get all the requested bytes, loop and try again.

Upvotes: 7

Related Questions