How to make two WebSocket servers listen on the same port?

1,989 views
Skip to first unread message

江源

unread,
Aug 11, 2020, 9:43:25 PM8/11/20
to WebSocket++
I create two threads and each runs a WebSocket server. Both listen on the same port.
When i run the below example, an error message shows "Address already in use".  
Thanks a lot~!

int main()
{
    int thread_num = 2;
    pthread_t tids[thread_num];
    
    for (int i = 0; i < thread_num; i++) {
        if (pthread(&tids[i], NULL, CreateServer, NULL) != 0) {
            cout << "Create WebSocket server " << i << ":failed!" << endl;
        }
    }
    
    pthread_exit(NULL);

    return 0;
}

void* CreateServer()
{
    // Create a server endpoint
    server echo_server;

    // Initialize ASIO
    echo_server.init_asio();

    // Register our message handler
    echo_server.set_message_handler(bind(&on_message,&echo_server,::_1,::_2));
    echo_server.set_http_handler(bind(&on_http,&echo_server,::_1));
    echo_server.set_tls_init_handler(bind(&on_tls_init,MOZILLA_INTERMEDIATE,::_1));
    echo_server.set_reuse_addr(true);

    // Listen on port 9002
    echo_server.listen(9002);

    // Start the server accept loop
    echo_server.start_accept();

    // Start the ASIO io_service run loop
    echo_server.run();
}

Peter Thorson

unread,
Aug 12, 2020, 7:15:54 PM8/12/20
to WebSocket++
Generally, you cannot have two servers listen on the same port of the same IP address as there is no way to determine which server should receive each connection. What are you trying to do?

If you just want a single server with a single listening socket on a single port to have its handlers served by multiple threads you can do that.

If you want to run multiple fully identical servers on a single port you can generate two servers on different ports and use load balancing software like HAProxy to split up traffic between them.
Reply all
Reply to author
Forward
0 new messages