美好的一天。所以,我有套接字:
if (WSAStartup(MAKEWORD(2, 2), &this->wsaData) != 0)
throw(errors::WSASTARTUP);
if ((this->serverSocket = socket(AF_INET, SOCK_STREAM, NULL)) == INVALID_SOCKET)
throw(errors::SOCKET_CREATING);
this->serverSocketAddr.sin_family = AF_INET;
this->serverSocketAddr.sin_port = htons(this->port);
this->serverSocketAddr.sin_addr.s_addr = INADDR_ANY;
if (bind(this->serverSocket, (sockaddr*)&this->serverSocketAddr, sizeof(this->serverSocketAddr)) == SOCKET_ERROR)
throw(errors::SOCKET_BINDING);
if (listen(this->serverSocket, SOMAXCONN) == SOCKET_ERROR)
throw(errors::SOCKET_LISTENING);
u_long mode = 1;
if (ioctlsocket(this->serverSocket, FIONBIO, &mode) == SOCKET_ERROR)
throw (errors::SOCKET_NONBLOCK);
尝试读取这样的传入消息:
std::string receive(SOCKET s) {
char buff[BUFF_SIZE];
int nOfReceivedBytes = 0;
nOfReceivedBytes = recv(s, buff, BUFF_SIZE, NULL);
if ((nOfReceivedBytes = recv(s, buff, BUFF_SIZE, NULL)) > 0) {
printMessage("Number of received bytes: %d\n", nOfReceivedBytes);
}
else if (nOfReceivedBytes == 0) {
printMessage("Connection is closed.\n");
return "";
}
else if (nOfReceivedBytes < 0 && errno != EWOULDBLOCK) {
printMessage("Receive failed.\n");
return "";
}
if (nOfReceivedBytes < BUFF_SIZE)
buff[nOfReceivedBytes] = '\0';
return std::string(buff);
}
当我逐步执行receive()
时,我收到了很好的消息而没有任何错误。
但如果我没有调试就这样做,我在这里errno == 1
else if (nOfReceivedBytes < 0 && errno != EWOULDBLOCK) {
printMessage("Receive failed.\n");
return "";
}
不调用ioctlsocket()
就可以了。如何解决?