我正在尝试创建一个多线程服务器,它将为每个连接的套接字创建一个新线程。我有它所以每次有连接时,都会创建一个新线程并从服务器向客户端发送一条消息,但我无法从客户端获得响应,无需获取10038 error
即可发送给服务器。我想让线程始终倾听并等待响应,直到它得到一个然后继续。这仍然可以在接受新连接时做到吗?
以下是我的代码的相关部分(我删除了很多套接字设置步骤)。
服务器代码:
DWORD WINAPI myThread(LPVOID lpParameter){
TCHAR recvBuffer[] = { 0 };
ZeroMemory(recvBuffer, sizeof(recvBuffer));
int recvBufferLen = 4096;
int iSendResult;
int iResult;
SOCKET ClientSocket1 = (SOCKET)lpParameter;
iResult = recv(ClientSocket1, (char*)recvBuffer, recvBufferLen, 0);
while (iResult > 0){
wprintf(L"Bytes received Port %d -> %s\n", iResult, recvBuffer);
}
wprintf(L"Not received\n");
return 0;
}
// Listen for connections
int _tmain(int argc, _TCHAR* argv[])
{
while (1){
ClientSocket1 = INVALID_SOCKET;
// Accept a Connection
while (ClientSocket1 == INVALID_SOCKET){
ClientSocket1 = accept(ListenSocket1, NULL, NULL);
}
wprintf(L"Client Connected. \n");
DWORD myThreadID;
HANDLE handle = CreateThread(0, 0, myThread, (LPVOID)ClientSocket1, 0, &myThreadID);
Sleep(10000);
}
return 0;
}
客户代码:
int _tmain(int argc, _TCHAR* argv[])
{
TCHAR recvBuffer[] = { 0 };
int recvBufferLen = 10000;
wchar_t sendBuf[] = { 0 };
int iSendResult;
// Receive Menu
iResult = recv(ConnectSocket1, (char*)recvBuffer, 512, 0);
if (iResult > 0){
wprintf(L"%s", recvBuffer);
// Send choice
do{
wprintf(L"Please input a choice:\n");
fgetws(sendBuf, 10, stdin);
} while (!(_wtoi(sendBuf) >= 1 && _wtoi(sendBuf) <= 6));
iSendResult = send(ConnectSocket1, (char*)sendBuf, 4096, 0);
if (iSendResult == SOCKET_ERROR){
wprintf(L"Send Failed: %d\n", WSAGetLastError());
closesocket(ConnectSocket1);
WSACleanup();
getchar();
return 1;
}
wprintf(L"Message Sent.\n");
}
}