简体   繁体   中英

Usage of read in socket programming

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.

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, eg here - see chapter 7.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM