c++ - 不能很好地使用send()和recv(),短字符串的第一个字节丢失了。c++

标签 c++ linux network-programming

我在linux中使用c++的send()和recv()。 我正在尝试制定某种协议(protocol)。它的某些部分的工作原理如下:

  1. A 连接到 B,B 创建线程并等待
  2. A 向 B 发送“备份”
  3. B 向 A 发送“OK”
  4. 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(以及类似的 writeread)在同步使用时(意味着应用程序在等待数据包时将被锁定),并且当数据包的大小已知时,应将其包装在如下循环中(写入示例):

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/

相关文章:

c++ - Flood_router6.c中的一些函数(BackTrack中的DoS程序)

c++ - 连接两个字符串c++

Linux脚本-用户真实姓名

linux - linux 上 rpath 规范的 @loader_path 等价物是什么?

c - 单独数据包中的 TCP FIN

C++使用For循环创建双向链表

带有模板类的 C++ 多态性

linux - 如何从shell脚本文件中删除mongo数据库的文件

c - 线程连接中的 TERMINATED 消息

c++ - 我应该使用哪个 TLS 库,可移植性是个问题