伯克利套接字发送成功时返回0
Berkeley Socket Send returning 0 on successful non-blocking send
我正在编写一个非阻塞聊天服务器,到目前为止服务器工作正常,但我不知道如何纠正部分发送,如果它们发生。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;
}
这样,你的代码将不断尝试发送所有的数据,直到发生错误,或者所有的数据都被成功发送。
相关文章:
- VS2017 版本 15.8.3 成功编译内联方法,而不返回所需值
- kill() 总是返回 0(成功),即使在子进程已经结束之后?
- Windows 函数"GetCursorInfo"返回成功,但光标的句柄为 NULL
- 数据不是用 ofstream 写入的,即使返回成功也是如此
- 谷歌测试:如何返回成功结果?
- ShellExecute 返回成功,但不执行文件
- 如何从函数返回成功或错误对象?
- MFC C++:IcmpSendEcho 成功返回,但状态为 IP_DEST_HOST_UNREACHABLE,并且 R
- posix_spawn创建一个僵尸进程并返回成功
- 超能力 NDK 安卓:返回 int 在"extern"块中成功,在调用函数中失败
- MsiViewFetch "SELECT * FROM `Property`"成功,但返回"Incorrect function." C++
- 内部异常处理程序,MessageBox()成功返回IDOK,但从未显示
- 致电Perror()首次成功,第二次返回非法寻求
- clCreateContext成功,但clCreateCommandQueue失败,返回-33
- 为什么WNetAddConnection2在成功调用WNetCancelConnection2后仍返回1219
- OpenCV VideoCapture::set()返回false,但成功
- HidD_GetManufacturerString和类似的函数返回成功,但不修改缓冲区
- QPixmap::save() 返回成功,但不生成任何文件
- 从c#中定义的COM类返回成功代码
- WriteFile函数返回成功,但无法查看文件系统中的文件