TCP client failed to send string to server

穿精又带淫゛_ 提交于 2019-12-11 08:16:22

问题


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.


回答1:


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.




回答2:


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).



来源:https://stackoverflow.com/questions/21720088/tcp-client-failed-to-send-string-to-server

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!