好的,我正在使用WinSockets2制作一个非常简单的服务器客户端应用程序。我初始化了我的套接字,我试图让服务器成为多用户。我几乎100%确定到目前为止,服务器套接字已正确形成,并且我100%确定客户端套接字是正确的,因为我将其用于另一台服务器。但是,recv
函数失败,错误为WSAENOTSOCK
。有问题的代码:
unsigned __stdcall client(void *data) {
SOCKET clientSocket = (SOCKET)data;
char inBuffer[DEFAULT_BUFLEN];
int inBytes = SOCKET_ERROR;
ZeroMemory(inBuffer, sizeof(inBuffer)); //make sure the buffer is 0
inBytes = recv(clientSocket, inBuffer, sizeof(inBuffer), 0);
printf("Client said: %s and there's this also %d\n", inBuffer, inBytes);
if (inBytes == SOCKET_ERROR) {
printf("eek! Something went wrong! %ld\n", WSAGetLastError());
}
return 0;
}
稍微低于它......
bool serverOn = true;
while (clientSocket = accept(listenSocket, NULL, NULL) && serverOn) {
//http://stackoverflow.com/questions/15185380/tcp-winsock-accept-multiple-connections-clients
unsigned threadID;
HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, &client, (void*)clientSocket, 0, &threadID);
}
if (iResult = shutdown(clientSocket, SD_SEND) == SOCKET_ERROR) { //clean up and end everything
printf("shutdown failed: %d\n", WSAGetLastError());
closesocket(clientSocket);
WSACleanup();
return 1;
}
closesocket(clientSocket);
WSACleanup();
return 0;
}
如果需要任何其他代码,请询问。谢谢!
答案 0 :(得分:-1)
好的,经过大量的试验和错误,我找到了答案。在此代码块中:
bool serverOn = true;
while (clientSocket = accept(listenSocket, NULL, NULL) && serverOn) {
//http://stackoverflow.com/questions/15185380/tcp-winsock-accept-multiple-connections-clients
unsigned threadID;
HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, &client, (void*)clientSocket, 0, &threadID);
}
if (iResult = shutdown(clientSocket, SD_SEND) == SOCKET_ERROR) { //clean up and end everything
printf("shutdown failed: %d\n", WSAGetLastError());
closesocket(clientSocket);
WSACleanup();
return 1;
}
closesocket(clientSocket);
WSACleanup();
return 0;
}
行while (clientSocket = accept(listenSocket, NULL, NULL) && serverOn) {
应分为两行,
while (serverOn) {
clientSocket = accept(listenSocket, NULL, NULL);
我想这与变量的范围有关。快乐的编码家伙!