Question

I am programming TCP server client. I sending the three string seperately using seperate send system call. But receiving end i getting only single string that is first string which i send. remaining two string missed.

Below i given the part of my server client program.

client.c

char *info = "infolog";
char *size = "filesize";
char *end = "fileend";
send(client, info, strlen(info)+1, 0);
send(client, size, strlen(size)+1, 0);
send(client, end, strlen(end)+1, 0);

server.c

while ((read_size = recv(client, msg, sizeof(msg), 0))) {
    printf("Data: %s\n", msg);
    memset(msg, 0, sizeof(msg));
}

Actual output:

Data: infolog

Expected output

Data: infolog
Data: filesize
Data: fileend

Thanks.

Was it helpful?

Solution

Try printing out read_size. You probably have received all the messages already.

Due to Nagle's Algorithm, the sender probably batched up your three send() calls and sent a single packet to the server. While you can disable Nagle's algorithm, I don't think it's a good idea in this case. Your server needs to be able to handle receiving of partial data, and handle receiving more data than it expects.

You might want to look into using an upper-layer protocol for your messages, such as Google Protocol Buffers. Take a look at the techniques page, where they describe how they might do it: build up a protocol buffer, and write its length to the stream before writing the buffer itself. That way the receive side can read the length and then determine how many bytes it needs to read before it has a complete message.

OTHER TIPS

TCP is not a message protocol but a byte stream protocol.

The three send-s could be recv-ed as a single input (or something else, e.g. in two or five recv etc....)

The application should analyze the input and buffer it to be able to splice it in meaningful messages.

the transmission may split or merge the messages, e.g. intermediate routers can and will split or merge the "packets".

In practice you'll better have some good conventions about your messages. Either decide that each message is e.g. newline terminated, or decide that it starts with some header giving its size.

Look at HTTP, SMTP, IMAP, SCGI or ONC/XDR (documented in RFC5531) as concrete examples. And document quite well your protocol (a minima, in long descriptive comments for some homework toy project, and more seriously, in a separate public document).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top