my client send msg like this:
vector<string> v({
"aa",
"bb",
"cc",
"dd"
});
for (;; Sleep(3000)) {
for (int i = 0; i < 4; ++i) {
send(clientSock, v[i].c_str(), v[i].size(), 0);
}
}
my server recv the msg like this:
for (;;) {
char recvbuf[256] = { 0 };
int ret = recv(sub_sock, recvbuf, 256, 0);
if (ret > 0) cout << recvbuf << endl;
}
my except behavior is that the server will recv 4 times,and cout 4 times.like:
"aa"
"bb"
"cc"
"dd"
But in fact the server only recv 2 times,and cout two times :
"aa"
"bbccdd"
TCP sockets are just streams of data and the data isn't packaged into messages. You could write many times and read it all with one recv
. In order to package the data into message, you need to include information about how much data each message contains. You could do it by supplying the size of the message payload at the beginning of the message:
sending
std::uint32_t size = htonl(v[i].size()); // convert to network byte order
send(clientSock, &size, sizeof(size), 0);
send(clientSock, v[i].c_str(), v[i].size(), 0);
receiving
std::uint32_t size;
std::string recvbuf;
recv(sub_sock, &size, sizeof(size), 0);
size = ntohl(size); // convert from network byte order
recvbuf.resize(size);
recv(sub_sock, recvbuf.data(), size, 0);
or you could use some sort of delimiter to separate the messages.