我正在尝试使用uwebsocket库创建服务器/客户端的最小示例。
在我下面的尝试中,服务器正在启动,它输出“服务器正在监听端口 9001”,但是客户端没有连接,客户端上没有任何 lambda 正在命中。
我还想知道当服务器重启时如何重新连接客户端。
#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;
}