Search code examples
c++multithreadingmutexc++17winsock

Accepting a socket in C++ behaving differently based on thread include


So I am trying to implement a server-client system in C++17 that also uses multithreading to deal with the clients. Thus far I managed to implement a basic outliner of it using Winsock2 for the server connections and the windows specific threads (CreateThread(...), etc...). And it's working fine.

Though since C++11 implemented it's own threads and we want to be able to run the system on Linux as well I decided to implement the threads that way, so I don't have the hassle of dealing with possix.

But pretty much it screwed up my thing and I don't know how to fix it. (note I am currently trying this on a local server, with both the "server" and the "client" running on the same machine).

So originally the system looked something like :

//set up connection / server details
while(true){
    newConnection = accept(sListen, (SOCKADDR*)&addr, &addrlen);
    if (newConnection == 0)
        {
         std::cout<<"Failed to accept the client's connection."" <<std::endl;
        }
        else
        {
        CreateThread(...);
        }
}

The problem is that if I include thread or mutex newConnection will accept a connection 24/7 even if there is none and it will always go in the else of the if. If I don't include thread and mutex the else of the if will be activated only when a client connects to the server.

Any ideas on how I could fix this or what might cause this problem?

Cheers

EDIT :

SOCKADDR_IN addr;
int addrlen = sizeof(addr); 

inet_pton(AF_INET, "127.0.0.1", &ip_address);
addr.sin_addr.s_addr = ip_address;
addr.sin_port = htons(1111); //Port
addr.sin_family = AF_INET; //IPv4 Socket

SOCKET sListen = socket(AF_INET, SOCK_STREAM, NULL); 
bind(sListen, (SOCKADDR*)&addr, sizeof(addr)); 
listen(sListen, SOMAXCONN);

EDIT 2 : I think the problem is that if I don't include <thread> or <mutex> the accept actually waits for a client to connect before it proceeds, while if I include it it just returns INVALID_SOCKET which seems to be equal to 4294967295.


Solution

  • Most implementations of the thread header will include (directly or otherwise) the functional header. That header declares std::bind. Unfortunately, if you also have...

    using namespace std;
    

    then there's a chance that std::bind will be preferred to the network related bind you're interested in.

    See also Why is “using namespace std” considered bad practice?.