Language: CPP
Networking
uWebSockets was created by Alexander Aaltonen (known as 'alexhultman') to address the inefficiencies of existing WebSocket libraries. Written in C++, it leverages event loops, modern epoll/kqueue, and optimized memory handling to achieve industry-leading performance. Today, it is used in large-scale production systems where latency and throughput are critical.
uWebSockets is a highly efficient C++ WebSocket and HTTP library designed for scalability and minimal resource usage. It supports millions of concurrent connections and powers some of the largest real-time applications, including trading platforms and messaging systems.
git clone https://github.com/uNetworking/uWebSockets.git && cd uWebSockets && makebrew install uwebsocketsvcpkg install uwebsocketsuWebSockets provides an event-driven API for handling WebSocket and HTTP connections. It allows developers to build high-performance servers that can handle millions of clients concurrently.
#include <uwebsockets/App.h>
int main() {
uWS::App().ws<false>("/", {
.open = [](auto* ws) {
std::cout << "A client connected" << std::endl;
},
.message = [](auto* ws, std::string_view message, uWS::OpCode opCode) {
ws->send("Hello, " + std::string(message), opCode);
}
}).listen(9001, [](auto* token) {
if (token) std::cout << "Listening on port 9001" << std::endl;
}).run();
}
A minimal WebSocket server that echoes back messages with a greeting.
uWS::App().get("/hello", [](auto* res, auto* req) {
res->end("Hello, HTTP!");
}).listen(8080, [](auto* token) {
if (token) std::cout << "Listening on port 8080" << std::endl;
}).run();Implements a simple HTTP endpoint responding with 'Hello, HTTP!'.
auto wsGroup = uWS::App().ws<false>("/chat", {
.message = [](auto* ws, std::string_view msg, uWS::OpCode opCode) {
ws->publish("chat", msg, opCode);
}
});Implements a chat room by broadcasting messages to all clients.
uWS::App().ws<false>("/", {
.message = [](auto* ws, std::string_view msg, uWS::OpCode) {
if (msg.size() > 1024) {
ws->send("Payload too large");
}
}
});Demonstrates handling and validating large incoming messages.
uWS::App().ws<false>("/", {
.open = [](auto* ws) { std::cout << "Secure connection!"; }
}).listen(9002, [](auto* token) { });Supports secure WebSocket (wss://) connections with TLS certificates.
uWS::App().ws<false>("/", {
.compression = uWS::SHARED_COMPRESSOR
});Enables per-message WebSocket compression to save bandwidth.
Use the correct event loop (epoll/kqueue) for your platform for best performance.
Enable per-message compression for bandwidth efficiency in large-scale apps.
Validate incoming data to prevent abuse (e.g., large payloads, invalid frames).
Leverage channels (`publish`/`subscribe`) for efficient broadcasting.
Use TLS in production to secure WebSocket and HTTP traffic.