我有一个无法解释的 recv()
函数问题:它总是返回 0。我有一个客户端/服务器应用程序,其中服务器只需接收一个字符串通过互联网(不同的电脑)从客户端。
没有连接问题,我还尝试将字符串从服务器发送到客户端:它有效。
我在博客中搜索,发现了recv() socket function returning data with length as 0 , non-blocking recv returns 0 when disconnected , Recv returning zero incorrectly ,并没有帮助我理解。
这里我发布了网络类: 网络.h
class Network
{
WSADATA wsaData;
WORD wVersionRequested;
int Port;
unsigned int byteReceived, byteSent;
SOCKET listeningSocket, connectedSocket;
SOCKADDR_IN serverAddr, senderInfo, clientAddr;
int caddrlen;
char buff[DIM];
string buffer;
public:
Network();
~Network();
void Recv();
};
网络.c
void Network::Recv() {
int n = recv(connectedSocket, buff, strlen(buff), 0);
setByteReceived(n);
buffer.assign(buff, n);
cout << "Buffer is: " << buff << endl;
if (byteReceived == 0)
cout << "\tConnection closed" << endl;
else if (byteReceived > 0) {
cout << "\tByte received: " << byteReceived << endl;
cout << getBuffer() << endl;
}
else {
myFormatMessage(WSAGetLastError());
}
}
最终的行为如下:客户端和服务器连接,服务器从recv()返回0。我还尝试在同一台机器上运行这两个程序。感谢您的帮助。
最佳答案
你有:
void Network::Recv() {
int n = recv(connectedSocket, buff, strlen(buff), 0);
...
如果strlen(buff)
返回0(因为buff
在索引0处包含一个空字节),您将询问recv()
读取 0 个字节,因此将返回 0 个字节。您应该使用 sizeof(buff)
而不是 strlen(buff)
。
关于c++ - recv() 始终返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39516683/