Is there any way to differentiate payloads from different packets while using blocking function read in c programming? I'm sending each message in a packet from TCP client and when i read(using read function) it in a TCP server i get all message together in a buffer without any delimiter in between.
-
3TCP is stream-oriented. There are no packets as far as your application is concerned, only an uninterrupted stream of bytes. Packets at the lower levels of the protocol can be split and merged by any intermediate party at will, so it would be meaningless to look at them.n. m. could be an AI– n. m. could be an AI2016-12-15 06:21:59 +00:00Commented Dec 15, 2016 at 6:21
2 Answers
You will have to implement that yourself on application layer.
One approach is for example Type-Length-Value.
Each message you send has following structure:
1 byte | 2 byte | length bytes
type length value
More details here.
Beware that read doesn't read exactly the number of bytes specified, it can read fewer - so you need to check its return value. For example see this.
There are also some gotchas with binary protocols you may want to be aware of.
Also it is advisable you do some background reading on network programming, e.g. here - see chapter 7.
7 Comments
TCP is stream oriented, which means that there is no packets which you could separate them, So you have to implement your protocol, for example you can send 4 bytes of header data before sending each packet and tell the receiver next packet size, in the receiving side you should always read a 4 byte header (which identifies next packet size) and make a blocking read with size specified in header.
Another option is to use fixed size packets, so every time you have to read fixed size packet from TCP buffer.
Unlike TCP, UDP is packet oriented, just as you want. in UDP packets are received in the size of sent and no other buffering or concatenations will happen, but its unreliable.