C++ と Winsock2 を使用して、サーバー アプリケーションとクライアント アプリケーションの両方を作成しました。現在、個別のスレッドを作成することにより、複数のクライアント接続を処理しています。
2 つのクライアントがサーバーに接続します。両方が接続された後、接続した最初のクライアントにのみメッセージを送信し、応答が受信されるまで待ってから、別のメッセージを 2 番目のクライアントに送信する必要があります。問題は、接続した最初のクライアントをターゲットにする方法がわからないことです。 現時点でコードは 2 つの接続を受け入れますが、メッセージはクライアント 2 に送信されます。
Send() を特定のクライアントに使用する方法について、誰かが私にアイデアを教えてもらえますか? ありがとう
接続を受け入れて新しいスレッドを開始するコード
SOCKET TempSock = SOCKET_ERROR; // create a socket called Tempsock and assign it the value of SOCKET_ERROR
while (TempSock == SOCKET_ERROR && numCC !=2) // Until a client has connected, wait for client connections
{
cout << "Waiting for clients to connect...\n\n";
while ((ClientSocket = accept(Socket, NULL, NULL)))
{
// Create a new thread for the accepted client (also pass the accepted client socket).
unsigned threadID;
HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, &ClientSession, (void*)ClientSocket, 0, &threadID);
}
}
クライアントセッション()
unsigned __stdcall ClientSession(void *data)
{
SOCKET ClientSocket = (SOCKET)data;
numCC ++; // increment the number of connected clients
cout << "Clients Connected: " << numCC << endl << endl; // output number of clients currently connected to the server
if (numCC <2)
{
cout << "Waiting for additional clients to connect...\n\n";
}
if (numCC ==2)
{
SendRender(); // ONLY TO CLIENT 1???????????
// wait for client render to complete and receive Done message back
memset(bufferReply, 0, 999); // set the memory of the buffer
int inDataLength = recv(ClientSocket,bufferReply,1000,0); // receive data from the server and store in the buffer
response = bufferReply; // assign contents of buffer to string var 'message'
cout << response << ". " << "Client 1 Render Cycle complete.\n\n";
SendRender(); // ONLY TO CLIENT 2????????????
}
return 0;
}
Sendrender() 関数 (レンダリング コマンドをクライアントに送信します)
int SendRender()
{
// Create message to send to client which will initialise rendering
char *szMessage = "Render";
// Send the Render message to the first client
iSendResult = send(ClientSocket, szMessage, strlen(szMessage), 0); // HOW TO SEND ONLY TO CLIENT 1???
if (iSendResult == SOCKET_ERROR)
{
// Display error if unable to send message
cout << "Failed to send message to Client " << numCC << ": ", WSAGetLastError();
closesocket(Socket);
WSACleanup();
return 1;
}
// notify user that Render command has been sent
cout << "Render command sent to Client " << numCC << endl << endl;
return 0;
}