WinSock 的 send() 总是返回 0 个已发送字节
我在使用 Winsock2 的 send() 函数时遇到了问题。无论我提供什么数据,send() 函数总是返回 0;例如,发送了 0 个字节,并且没有错误。我已经用谷歌搜索了一段时间,但尚未找到解决方案。我已检查发送的数据格式是否正确,并且向其传递了有效的套接字。
这是错误所在的代码片段(至少我认为):
//Send HTTP header to server
#define MAX_HEADER_LEN 512
#ifdef UNICODE
char* cpHost = (char*)malloc(sizeof(char) * (_tcslen(cpServer)+1));
wcstombs(cpHost, cpServer, _tcslen(cpServer));
cpHost[_tcslen(cpServer)] = '\0';
#else
char* cpHost = cpServer;
#endif
char cpHeader[MAX_HEADER_LEN];
sprintf(cpHeader, "GET %s HTTP/1.1\r\nHost: %s\r\n\r\n", "/", cpHost);
#ifdef UNICODE
free(cpHost);
#endif
//Send the HTTP request to the sever
int iSent;
if(iSent = send(servSocket, cpHeader, strlen(cpHeader), 0) == SOCKET_ERROR)
{
_tprintf(TEXT("Error sending header to server: %d\n"), WSAGetLastError());
WSACleanup();
return 2;
}
_tprintf(TEXT("Sent '%d' bytes\n"), iSent);
return 0;
有什么想法导致这种行为吗?
这是该文件的完整源代码(请原谅所有不良的编码习惯): http://pastebin.com/URsaFz0Q
感谢您的帮助, ——迪伦
I've been experiencing a problem with the Winsock2's function send(). No matter what data I provide it, the send() function always returns 0; eg 0 bytes sent, and no errors. I've google searched for a while now, but have yet to find a solution. I've checked that the data being send is correctly formatted, and I'm passing it a valid socket.
Here is a snippet of the code which the bug resides in (I would think at least):
//Send HTTP header to server
#define MAX_HEADER_LEN 512
#ifdef UNICODE
char* cpHost = (char*)malloc(sizeof(char) * (_tcslen(cpServer)+1));
wcstombs(cpHost, cpServer, _tcslen(cpServer));
cpHost[_tcslen(cpServer)] = '\0';
#else
char* cpHost = cpServer;
#endif
char cpHeader[MAX_HEADER_LEN];
sprintf(cpHeader, "GET %s HTTP/1.1\r\nHost: %s\r\n\r\n", "/", cpHost);
#ifdef UNICODE
free(cpHost);
#endif
//Send the HTTP request to the sever
int iSent;
if(iSent = send(servSocket, cpHeader, strlen(cpHeader), 0) == SOCKET_ERROR)
{
_tprintf(TEXT("Error sending header to server: %d\n"), WSAGetLastError());
WSACleanup();
return 2;
}
_tprintf(TEXT("Sent '%d' bytes\n"), iSent);
return 0;
Any ideas what is causing this behavior?
Here is the full source of the file (pardon all the bad coding habits):
http://pastebin.com/URsaFz0Q
Thanks for your help,
--Dylan
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果成功,您的代码会将
iSent
设置为零。成功时,send
不会返回 SOCKET_ERROR,因此send(...)==SOCKET_ERROR
为 false。 C 中 False 为零。更改
为:
或:
Your code sets
iSent
to zero on success. On success,send
doesn't return SOCKET_ERROR, sosend(...)==SOCKET_ERROR
is false. False is zero in C.Change:
To:
Or: