我在linux中使用c++的send()和recv()。 我正在尝试制定某种协议(protocol)。它的某些部分的工作原理如下:
- A 连接到 B,B 创建线程并等待
- A 向 B 发送“备份”
- B 向 A 发送“OK”
- A 向 B 发送(类似字符串)“20001”。
在最后(第4)步中,A 向 B 发送了一个短字符串,小于 10 个字节。 然而,当A发送“20001”给B时,B接收到“0001”,第一个字节丢失了,我只调用了一次recv()。 我检查了长度,A发送6个字节,B接收18或19个字节,B使用的缓冲区是20个字节长。一些代码:
send(datasock,conferenceid.c_str(),conferenceid.size()+1,0);//A send conferenceid,sent "20001" and returned 6 in the tests
char temp[20]={0};//B recv data
memset(temp,0,20);
recv(remote->sock_fd,temp,20,0);//got "0001" and returned 18 or 19 in the tests
问题是,几个小时前,在我的程序的其他部分,当发送“10001”时,收到“001”。不知何故,几个小时后,它现在运行良好。 我对网络编程不熟悉。有人可以告诉我在哪里可以找到丢失的字节吗?
最佳答案
来自人工发送
RETURN VALUE
On success, these calls return the number of characters sent. On error, -1 is returned, and errno is set appropriately.
send
以及 recv
(以及类似的 write
和 read
)在同步使用时(意味着应用程序在等待数据包时将被锁定),并且当数据包的大小已知时,应将其包装在如下循环中(写入示例):
int write_all(int fd, const char *buf, int n)
{
int pos = 0;
while (pos < n)
{
int cnt = write(fd, buf + pos, n - pos);
if (cnt < 0)
{
perror("write_all");
exit(1);
}
if (cnt > 0)
{
pos += cnt;
}
}
return 0;
}
关于c++ - 不能很好地使用send()和recv(),短字符串的第一个字节丢失了。c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27636958/