c++windowswebsocketuwebsockets

How to create a websocket server/client using the uwebsocket lib?


I'm tyring to create a minimal example of a server/client using the uwebsocket lib.

On my attempt below the server is getting on, it outputs "Server listening on port 9001", but the client is not connecting, no one lambda on the client is hitting.

I also would like to know how to reconnect the client when the server restart.

#include <uwebsockets/App.h>
#include <thread>
#include <iostream>

class Server
{
public:
    bool connected = false;
    void runServer()
    {
        uWS::App().ws<Server>("/*", 
        {
            .open = [this](auto* ws) 
            {
                ws->subscribe("broadcast");
                std::cout << "Server: Client connected" << std::endl;
            },
            .message = [](auto* ws, std::string_view message, uWS::OpCode opCode)
            {
                ws->publish("broadcast", message, opCode);
                std::cout << "Server: Received and broadcast message: " << message << std::endl;
            },
            .close = [](auto* ws, int code, std::string_view message)
            {
                std::cout << "Server: Client disconnected" << std::endl;
            }
        }).listen(9001, [this](auto* listen_socket)
        {
            if (listen_socket) 
            {
                std::cout << "Server listening on port 9001" << std::endl;
                connected = true;
            }
        }).run();
    }
};

class Client
{
public:
    void runClient() 
    {
        uWS::App().ws<Client>("/*",  uWS::App::WebSocketBehavior<Client>
        {
            .open = [this](auto* ws) 
            {
                std::cout << "Client: Connected to server" << std::endl;
                ws->send("Hello from client!", uWS::OpCode::TEXT);
            },
            .message = [](auto* ws, std::string_view message, uWS::OpCode opCode)
            {
                std::cout << "Client: Received message: " << message << std::endl;
            },
            .close = [](auto* ws, int code, std::string_view message)
            {
                std::cout << "Client: Disconnected from server" << std::endl;
            }
        }).connect("ws://localhost:9001", nullptr).run();
    }
};



int main()
{
    Server server;
    std::thread server_thread([&server]() { server.runServer(); });

    while (!server.connected)
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }

    Client client;
    client.runClient();

    server_thread.join();
    return 0;
}

Solution

  • the client is not connecting

    These issues say uWebSockets does not support a client mode:

    https://github.com/uNetworking/uWebSockets/issues/1594

    https://github.com/uNetworking/uWebSockets/issues/1763