我有一个 recv()
函数的问题,我可以't explain: it always returns 0. I'一个客户端/服务器应用程序,其中服务器只需要通过互联网(不同的PC)从客户端接收一个字符串 .
没有连接问题,我也试图从服务器发送一个字符串到客户端:它工作 . 我在博客中搜索,我找到了什么,recv() socket function returning data with length as 0,non-blocking recv returns 0 when disconnected,Recv returning zero incorrectly,没有帮助我理解 .
在这里我发布网络类:Network.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();
};
Network.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 . 我也尝试在同一台机器上运行这两个程序 . 谢谢您的帮助 .
1 回答
你有:
如果
strlen(buff)
返回0(因为buff
在索引0处包含空字节),您将要求recv()
读取0个字节,因此它将返回0个字节 . 您应该使用sizeof(buff)
而不是strlen(buff)
.