TCP 客户端无法向服务器发送字符串 [英] TCP client failed to send string to server

查看:58
本文介绍了TCP 客户端无法向服务器发送字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写 TCP 服务器客户端.我使用单独的 send 系统调用分别发送三个字符串.但是接收端我只得到单个字符串,这是我发送的第一个字符串.遗漏了剩下的两个字符串.

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));
}

实际输出:

Data: infolog

预期输出

Data: infolog
Data: filesize
Data: fileend

谢谢.

推荐答案

尝试打印出read_size.您可能已经收到了所有消息.

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

由于Nagle 算法,发件人可能将您的三个发送() 调用并向服务器发送单个数据包.虽然您可以禁用 Nagle 的算法,但我认为在这种情况下这不是一个好主意.您的服务器需要能够处理部分数据的接收,并处理接收的数据超出预期.

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.

您可能需要考虑为您的消息使用上层协议,例如 Google协议缓冲区.看看技术页面,他们在那里描述了他们如何做:建立一个协议缓冲区,并在写入缓冲区本身之前将其长度写入流.这样接收端就可以读取长度,然后确定需要读取多少字节才能得到完整的消息.

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.

这篇关于TCP 客户端无法向服务器发送字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆