c++ - tcp 连接上的 recv() 问题

标签 c++ windows sockets send recv

我正在用 C 语言在 Windows 上模拟 TCP 通信。 我有发送者和接收者在通信。

发送方向接收方发送特定大小的数据包。接收方获取它们并将收到的每个数据包的 ACK 发送回发送方。 如果发送方没有收到特定的数据包(它们在数据包内的 header 中编号),它会再次将数据包发送给接收方。 这是接收方的 getPacket 函数:

//get the next packet from the socket. set the packetSize to -1
//if it's the first packet.
//return: total bytes read
// return: 0 if socket has shutdown on sender side, -1 error, else number of bytes received
int getPakcet(char* chunkBuff, int packetSize, SOCKET AcceptSocket)
{
    int totalChunkLen = 0;
    int bytesRecv = -1;
    bool firstTime = false;

    if(packetSize == -1)
    {
        packetSize = MAX_PACKET_LENGTH;
        firstTime = true;
    }

    int needToGet = packetSize;

    do
    {
        char* recvBuff;
        recvBuff = (char*)calloc(needToGet, sizeof(char));

        if(recvBuff == NULL)
        {
            fprintf(stderr, "Memory allocation problem\n");
            return -1;
        }

        bytesRecv = recv(AcceptSocket, recvBuff, needToGet, 0);

        if(bytesRecv == SOCKET_ERROR)
        {
            fprintf(stderr, "recv() error %ld.\n", WSAGetLastError());
            totalChunkLen = -1;
            return -1;
        }

        if(bytesRecv == 0)
        {
            fprintf(stderr, "recv(): socket has shutdown on sender side");
            return 0;
        }
        else if(bytesRecv > 0)
        {
            memcpy(chunkBuff + totalChunkLen, recvBuff, bytesRecv);
            totalChunkLen += bytesRecv;
        }

        needToGet -= bytesRecv;
    }
    while((totalChunkLen < packetSize) && (!firstTime));

    return totalChunkLen;
}

我使用 firstTime因为第一次接收方不知道发送方要发送给它的正常包裹大小,所以我使用 MAX_PACKET_LENGTH获取一个包,然后将正常的包大小设置为我收到的字节数。

我的问题是最后一个包。 它的尺寸小于包装尺寸。 所以假设最后一个包装尺寸是 2,正常包装尺寸是 4。 所以recv()得到两个字节,继续 while 条件,然后是 totalChunkLen < packetSize因为2<4所以它再次迭代循环并卡在 recv() 中因为它正在阻塞,因为发件人没有任何东西可以发送。

在发送端,我无法关闭连接,因为我没有收到 ACK,所以这是一个死锁。接收方被卡住,因为它正在等待更多的包裹,但发件人没有要发送的东西。

我不想为 recv() 使用超时或者在包头中插入一个特殊字符来标记它是最后一个。

我能做什么?

最佳答案

您正在使用 TCP 在接收器和发送器之间进行通信,而 TCP 是一种面向流的协议(protocol)。也就是说,您在一端放置一个字节流,然后在另一端按顺序无损地输出流。无法保证每个 send() 都会匹配另一端的 recv(),因为数据可能会因各种原因而中断。

因此,如果您使用 TCP 连接执行以下操作:

char buffer[] = "1234567890";
send(socket, buffer, 10, 0);

然后在接收器上:

char buffer[10];
int bytes = recv(socket, buffer, 10, 0);

当 recv() 返回时,字节可以是 0 到 10 之间的任何值。

TCP 在 IP 上运行,IP 是一种面向数据报的协议(protocol)。这就是为什么 TCP 实现可以假定当它发送数据报时它将在另一端接收到整个数据报(或者可能不会,或者乱序接收)。如果你想模拟你至少有两个选择:

  1. 将帧添加到您的 TCP 消息中,以便您可以从中提取数据包。这涉及将诸如数据包大小之类的内容添加到您发送到流中的 header 中。使用它来模拟 TCP 是没有意义的,因为您的所有数据包总是按顺序到达,并且已经使用了底层的 TCP 流量控制/拥塞避免机制。
  2. 使用 UDP 等数据报协议(protocol)。这将更接近 TCP 运行的 IP 层。

你可能应该选择选项 2,但如果你想通过 TCP 进行成帧路由,你可以,例如(粗略的快速代码如下):

// We do this to communicate with machines having different byte ordering
u_long packet_size = htonl(10); // 10 bytes packet
send(socket, &packet_size, 4, 0); // First send the frame size
send(socket, buffer, 10, 0); // Then the frame

接收端:

u_long packet_size; // Hold the size of received packet
int bytes_to_read = 4; // We send 4 bytes on the wire for size and expect 4
int nresult; // hold result of recv()
char *psize = &packet_size; // Point to first byte of size
while( bytes_to_read ) // Keep reading until we have all the bytes for the size
{
  nresult = recv(socket, psize, bytes_to_read, 0);
  if(nresult==0) deal with connection closed.
  bytes_to_read -= nresult;
  psize += nresult;
}
packet_size = ntohl(packet_size);
// Now we know the packet size we can proceed and read it similar to above

关于c++ - tcp 连接上的 recv() 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5211473/

相关文章:

c++ - CRTP和重载返回类型推导

Android NDK 在 JNI 中引用外部库

c++ - 我如何测试我的谷歌验证器的实现?

c++ - 使用 select() 请求/回复服务器。无法写回客户端

c++ - 如何更改 DLL 中的过程名称

c++ - 在opencv中相应地对blob进行排序

c++ - windows下lapack的使用方法

windows - 在 Windows 上的 PostgreSQL 的单个事务中运行多个 SQL 文件

c++ - QTcp 服务器 : bind socket with custom options

javascript - InDesign CS6 套接字返回空