1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
|
...
SOCKET ClientSocket[5];
...
int main()
{
...
listen(ListenSocket);
return 0;
}
int listen(SOCKET ListenSocket)
{
...
for (int i = 1; i < 5; i++)
{
std::cout << 10 << std::endl;
iResult = listen(ListenSocket, SOMAXCONN);
if (iResult == SOCKET_ERROR) {
std::cout << 11 << std::endl;
printf("listen failed with error: %d\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
return -1;
}
std::cout << 23 << std::endl;
bool is_accepting = true;
while(is_accepting)
{
accept(ListenSocket);
}
for (auto it : thread_vec) it->join();
return 0;
}
int accept(SOCKET ListenSocket)
{
// Accept a client socket
std::cout << 12 << std::endl;
std::cout << 13 << std::endl;
SOCKET client_socket = accept(ListenSocket, NULL, NULL);
if (client_socket == INVALID_SOCKET)
{
printf("accept failed with error: %d\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
return 1;
}
else{
std::cout << "Client connected" << std::endl;
}
sendReceiveThread[currentNumClients] = new std::thread([client_socket](){sendReceive(client_socket); }); // Note: Passing client_socket
(*sendReceiveThread[currentNumClients]).join();
delete sendReceiveThread[currentNumClients];
return 0;
}
int sendReceive(SOCKET client_socket) // Note
{
int currentNumClients = numClients;
int iSendResult;
char recvbuf[DEFAULT_BUFLEN];
int recvbuflen = DEFAULT_BUFLEN;
// Receive until the peer shuts down the connection
while(true)
{
std::cout << 14 << std::endl;
iResult = recv(client_socket, recvbuf, recvbuflen, 0);
std::cout << iResult << std::endl;
if (iResult > 0) {
std::cout << 15 << std::endl;
printf("Bytes received: %d\n", iResult);
// Echo the buffer back to the clients
std::cout << 16 << std::endl;
for (int i = 1; i <= numClients; i++)
{
iSendResult = send(client_socket, recvbuf, iResult, 0); // Note
if (iSendResult == SOCKET_ERROR) {
std::cout << 17 << std::endl;
printf("send failed with error: %d\n", WSAGetLastError());
closesocket(client_socket); // Note
WSACleanup();
return 1;
}
printf("Bytes sent: %d\n", iSendResult);
}
}
else if (iResult == 0) {
std::cout << 18 << std::endl;
printf("Connection closing...\n");
break;
}
else {
std::cout << 19 << std::endl;
printf("recv failed with error: %d\n", WSAGetLastError());
std::cout << "On client #" << currentNumClients << std::endl;
break;
}
}
iResult = shutdownFunction(client_socket); // Note
std::cout << 22 << std::endl;
// cleanup
closesocket(client_socket); // Note
WSACleanup();
return 0;
}
...
|