伯克利套接字发送成功时返回0

Berkeley Socket Send returning 0 on successful non-blocking send

本文关键字:返回 成功 套接字 伯克利      更新时间:2023-10-16

我正在编写一个非阻塞聊天服务器,到目前为止服务器工作正常,但我不知道如何纠正部分发送,如果它们发生。send(int, char*, int);函数发送成功时总是返回0,发送失败时总是返回-1。我读过的每个文档/手册页都说它应该返回实际馈送到网络缓冲区的字节数。我已经检查了,确保我可以反复发送到服务器并接收回数据,没有问题。

这是我用来调用send的函数。我都尝试先将返回数据打印到控制台,然后在返回的ReturnValue上尝试断行;当调试。同样的结果,ReturnValue总是0或-1;
int Connection::Transmit(string MessageToSend)
{         
    // check for send attempts on a closed socket
    // return if it happens.
    if(this->Socket_Filedescriptor == -1)
        return -1;
    // Send a message to the client on the other end
    // note, the last parameter is a flag bit which 
    // is used for declaring out of bound data transmissions.
    ReturnValue  = send(Socket_Filedescriptor,
                         MessageToSend.c_str(),
                         MessageToSend.length(),
                         0); 
    return ReturnValue;        
}

你为什么不试着发送一个循环呢?例如:

int Connection::Transmit(string MessageToSend)
{         
    // check for send attempts on a closed socket
    // return if it happens.
    if(this->Socket_Filedescriptor == -1)
        return -1;
    int expected = MessageToSend.length();
    int sent     = 0;
    // Send a message to the client on the other end
    // note, the last parameter is a flag bit which 
    // is used for declaring out of bound data transmissions.
    while(sent < expected) {
      ReturnValue  = send(Socket_Filedescriptor,
                         MessageToSend.c_str() + sent, // Send from correct location
                         MessageToSend.length() - sent, // Update how much remains
                         0); 
      if(ReturnValue == -1)
        return -1; // Error occurred
      sent += ReturnValue;
    }
    return sent;        
}

这样,你的代码将不断尝试发送所有的数据,直到发生错误,或者所有的数据都被成功发送。