Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ TCP socket multiple write() on server side treated as single read on client side

Tags:

c++

tcp

sockets

I'm developing a program with TCP connection, which consists of a server and multiple clients.

Server side

write(sockFd,message,strlen(message));
write(sockFd,message2,strlen(message2));

Client side

char msg[256];

bzero(msg, 256);
n = read (listenFd, msg, 255);
cout << "Msg1 " << msg << endl;

bzero(msg, 256);
n = read (listenFd, msg, 255);
cout << "Msg2 " << msg << endl;

The problem is after the server write() the two messages, the first read() on the client(s) may read all of messages from server. For example, the output is Msg 1 content-of-msg1content-of-msg2. Why it can happen?

like image 776
ZZZ Avatar asked Nov 19 '25 00:11

ZZZ


1 Answers

TCP is a streaming protocol so data comes as a stream, this means that each read will read as much data as there is in the buffer (or as much as you requested).

So if you want to break the data down into packets or datagrams, you will need to do so with your own session based protocol. One way of doing this is prefixing the outgoing data with 4 bytes of length. This way the reader can first read the length and that way know how big the rest of the datagram is.

like image 152
doron Avatar answered Nov 21 '25 13:11

doron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!