user2367115
user2367115

Reputation: 53

C++ multithreaded server with winsock and std::thread

I have some problem with including thread module, when I add:

#include <thread>

the call to the bind function gives me error:

Error 3 error C2440: '=' : cannot convert from 'std::_Bind<_Forced,_Ret,_Fun,_V0_t,_V1_t,_V2_t,_V3_t,_V4_t,_V5_t,>' to 'int' c:\users\ohadpeled\documents\visual studio 2012\projects\loginserver\loginserver\server.cpp 87 1 LoginServer 4 IntelliSense: no suitable conversion function from "std::_Bind" to "int" exists c:\Users\OhadPeled\Documents\Visual Studio 2012\Projects\LoginServer\LoginServer\Server.cpp 87 20 LoginServer

I don't understand why it cause this error, without including the thread module the call works fine. I'd be happy if someone will explain me what cause it.

Here is part of the server class:

            /* Set TCP listening socket */
            ListenResult = bind(ListenSocket, result->ai_addr, (int)result->ai_addrlen); // Error in this line
            if (ListenResult != SOCKET_ERROR) 
            {
                freeaddrinfo(result);

                ListenResult = listen(ListenSocket, SOMAXCONN);
                if (ListenResult != SOCKET_ERROR) 
                {
                    /* Accepting clients */
                    while(true)
                    {
                        ClientSocket = new SOCKET();
                        ADDR = new SOCKADDR_IN();
                        ADDRSize = sizeof(*ADDR);
                        *ClientSocket = accept(ListenSocket, (struct sockaddr*)ADDR, &ADDRSize);
                        if (*ClientSocket != INVALID_SOCKET) 
                        {
                            /* I want to thread the handler function over here! */
                            Handler(ClientSocket, ADDR);
                        }
                    }
                }
            }

I'm using win7, and set the socket with winsock.

Upvotes: 1

Views: 3058

Answers (1)

Adam Rosenfield
Adam Rosenfield

Reputation: 400642

The problem is that the compiler is resolving the bind symbol to the C++ function std::bind() instead of the WinSock function bind(). In order to fix this, you can do one of two things:

  1. Remove all using namespace std; declarations in your source file; or
  2. Use the scope resolution operator :: to explicitly refer to the bind function in the global namespace:

    ListenResult = ::bind(...);
    

Upvotes: 9

Related Questions