N
N
NeoLight22020-12-30 10:18:29
C++ / C#
NeoLight2, 2020-12-30 10:18:29

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();
}


And here is the code of the function that processes each client:
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);
    }
}

But for some reason the accept() function doesn't want to delay the code until the client connects, but just plays in a loop without waiting for the client (
Where did I go wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Ananiev, 2020-12-30
@SaNNy32

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 question

Ask a Question

731 491 924 answers to any question