Answer the question
In order to leave comments, you need to log in
accept() function; does not block code, in C++, what should I do?
I want to write a simple TCP server in C ++, so that it listens to connections to it in one thread, and then allocates a new thread for each new client.
I wrote similar code:
void startServer() {
int wsaStatus;
WSADATA WSAData;
wsaStatus = WSAStartup(MAKEWORD(2, 0), &WSAData);
if (wsaStatus != NO_ERROR) {
cout << "WSA Startup failed with error : " << wsaStatus;
}
SOCKET sock;
SOCKADDR_IN sin;
sin.sin_addr.s_addr = htonl(INADDR_ANY);
sin.sin_family = AF_INET;
sin.sin_port = htons(1234);
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == INVALID_SOCKET) {
std::cout << "INVALID SOCKET " << WSAGetLastError();
WSACleanup();
}
bind(sock, (SOCKADDR*)&sin, sizeof(sin));
listen(sock, 1000);
while (true)
{
int sizeof_sin = sizeof(sin);
sock = accept(sock, (SOCKADDR*)&sin, &sizeof_sin);
thread clientThread(serveClient, sock); //под каждого нового клиента выделяю новый поток
clientThread.detach();
cout << "CONNECTION ESTABLISHED!" << endl;
}
WSACleanup();
}
void serveClient(SOCKET socket) {
char buffer[255];
if (socket != INVALID_SOCKET)
{
recv(socket, buffer, sizeof(buffer), 0);
closesocket(socket);
std::cout << buffer << std::endl;
}
else {
closesocket(socket);
}
}
Answer the question
In order to leave comments, you need to log in
We need to check what accept returns for an error.
https://docs.microsoft.com/en-us/windows/win32/api...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question