uWebSockets
Simple, secure & standards compliant web server for the most demanding of applications
Top Related Projects
Tiny WebSocket library for Go.
Quick Overview
uWebSockets is a highly scalable, event-driven, non-blocking WebSocket & HTTP server library for C++11 and C++14. It is designed to be lightweight, fast, and efficient, making it a popular choice for building high-performance network applications.
Pros
- High Performance: uWebSockets is known for its exceptional performance, with benchmarks showing it can handle millions of concurrent connections with low CPU and memory usage.
- Cross-Platform: The library is cross-platform, supporting Windows, macOS, and Linux, making it easy to develop and deploy applications on different platforms.
- Asynchronous and Event-Driven: uWebSockets uses an asynchronous, event-driven architecture, which allows it to handle a large number of concurrent connections efficiently.
- Lightweight and Modular: The library is designed to be lightweight and modular, with a small footprint and the ability to include only the features needed for a specific application.
Cons
- Limited Documentation: While the project has a GitHub repository with some documentation, the overall documentation could be more comprehensive, making it challenging for new users to get started.
- Steep Learning Curve: Developing applications with uWebSockets may have a steeper learning curve, especially for developers who are not familiar with C++ or event-driven programming.
- Lack of Widespread Adoption: Compared to some other popular WebSocket and HTTP server libraries, uWebSockets may not have the same level of widespread adoption and community support.
- Potential Compatibility Issues: As a C++ library, uWebSockets may have some compatibility issues with certain platforms or compilers, which could make it more difficult to integrate into existing projects.
Code Examples
Here are a few short code examples demonstrating the usage of uWebSockets:
- WebSocket Server:
#include <uWS/uWS.h>
int main() {
uWS::Hub h;
h.onMessage([](uWS::WebSocket<uWS::SERVER>* ws, char* message, size_t length, uWS::OpCode opCode) {
// Handle incoming WebSocket messages
std::cout << "Received message: " << std::string(message, length) << std::endl;
ws->send(message, length, opCode);
});
h.listen(3000);
h.run();
return 0;
}
- HTTP Server:
#include <uWS/uWS.h>
int main() {
uWS::Hub h;
h.onHttpRequest([](uWS::HttpResponse* res, uWS::HttpRequest req, char* data, size_t length, size_t remainingBytes) {
// Handle incoming HTTP requests
res->end("Hello, World!");
});
h.listen(3000);
h.run();
return 0;
}
- WebSocket Client:
#include <uWS/uWS.h>
int main() {
uWS::Hub h;
h.connect("ws://echo.websocket.org", [](uWS::WebSocket<uWS::CLIENT>* ws) {
// Handle WebSocket connection
ws->send("Hello, WebSocket!", 17, uWS::OpCode::TEXT);
});
h.run();
return 0;
}
- Handling WebSocket Disconnections:
#include <uWS/uWS.h>
int main() {
uWS::Hub h;
h.onDisconnection([](uWS::WebSocket<uWS::SERVER>* ws, int code, char* message, size_t length) {
// Handle WebSocket disconnections
std::cout << "WebSocket disconnected with code " << code << " and message: " << std::string(message, length) << std::endl;
});
h.listen(3000);
h.run();
return 0;
}
Getting Started
To get started with uWebSockets, you'll need to have a C++11 or C++14 compatible compiler installed. You
Competitor Comparisons
Tiny WebSocket library for Go.
Pros of ws
- Written in Go, offering excellent concurrency and performance
- Lightweight and minimalistic design
- Flexible and customizable, allowing low-level control
Cons of ws
- Less feature-rich out of the box compared to uWebSockets
- May require more manual implementation for advanced features
- Smaller community and ecosystem
Code Comparison
ws:
conn, _, _, err := ws.DefaultDialer.Dial(ctx, "ws://example.com")
if err != nil {
// Handle error
}
defer conn.Close()
uWebSockets:
uWS::Hub h;
h.onConnection([](uWS::WebSocket<uWS::SERVER> *ws, uWS::HttpRequest req) {
// Handle connection
});
h.listen(3000);
Key Differences
- Language: ws is written in Go, while uWebSockets is in C++
- Performance: Both offer high performance, but uWebSockets may have an edge in raw speed
- Features: uWebSockets provides more built-in features and abstractions
- Ecosystem: uWebSockets has a larger community and more extensive documentation
- Use cases: ws is ideal for Go projects requiring fine-grained control, while uWebSockets is well-suited for high-performance C++ applications
Both libraries are excellent choices for WebSocket implementations, with the selection depending on project requirements, language preference, and desired level of abstraction.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Simple, secure1 & standards compliant2 web server for the most demanding3 of applications. Read more...
:closed_lock_with_key: Optimized security
Being meticulously optimized for speed and memory footprint, µWebSockets is fast enough to do encrypted TLS 1.3 messaging quicker than most alternative servers can do even unencrypted, cleartext messaging3.
Furthermore, we partake in Google's OSS-Fuzz with a ~95% daily fuzzing coverage4 with no sanitizer issues. LGTM scores us flawless A+ from having zero CodeQL alerts and we compile with pedantic warning levels.
:arrow_forward: Rapid scripting
µWebSockets is written entirely in C & C++ but has a seamless integration for Node.js backends. This allows for rapid scripting of powerful apps, using widespread competence. See µWebSockets.js.
:crossed_swords: Battle proven
We've been fully standards compliant with a perfect Autobahn|Testsuite score since 20162. µWebSockets powers many of the biggest crypto exchanges in the world, handling trade volumes of multiple billions of USD every day. If you trade crypto, chances are you do so via µWebSockets.
:battery: Batteries included
Designed around a convenient URL router with wildcard & parameter support - paired with efficient pub/sub features for WebSockets. µWebSockets should be the obvious, complete starting point for any real-time web project with high demands.
Start building your Http & WebSocket apps in no time; read the user manual and see examples. You can browse our TypeDoc for a quick overview.
/* One app per thread; spawn as many as you have CPU-cores and let uWS share the listening port */
uWS::SSLApp({
/* These are the most common options, fullchain and key. See uSockets for more options. */
.cert_file_name = "cert.pem",
.key_file_name = "key.pem"
}).get("/hello/:name", [](auto *res, auto *req) {
/* You can efficiently stream huge files too */
res->writeStatus("200 OK")
->writeHeader("Content-Type", "text/html; charset=utf-8")
->write("<h1>Hello ")
->write(req->getParameter("name"))
->end("!</h1>");
}).ws<UserData>("/*", {
/* Just a few of the available handlers */
.open = [](auto *ws) {
ws->subscribe("oh_interesting_subject");
},
.message = [](auto *ws, std::string_view message, uWS::OpCode opCode) {
ws->send(message, opCode);
}
}).listen(9001, [](auto *listenSocket) {
if (listenSocket) {
std::cout << "Listening on port " << 9001 << std::endl;
} else {
std::cout << "Failed to load certs or to bind to port" << std::endl;
}
}).run();
:briefcase: Commercially supported
uNetworking AB is a Swedish consulting & contracting company dealing with anything related to µWebSockets; development, support and customer success.
Don't hesitate sending a mail if you're building something large, in need of advice or having other business inquiries in mind. We'll figure out what's best for both parties and make sure you're not falling into common pitfalls.
Special thanks to BitMEX, Bitfinex, Google, Coinbase, Bitwyre, AppDrag and deepstreamHub for allowing the project itself to thrive on GitHub since 2016 - this project would not be possible without these beautiful companies.
:wrench: Customizable architecture
µWebSockets builds on µSockets, a foundation library implementing eventing, networking and cryptography in three different layers. Every layer has multiple implementations and you control the compiled composition with flags. There are currently five event-loop integrations; libuv, ASIO, GCD and raw epoll/kqueue.
In a nutshell:
WITH_WOLFSSL=1 WITH_LIBUV=1 make examples
builds examples utilizing WolfSSL and libuvWITH_OPENSSL=1 make examples
builds examples utilizing OpenSSL and the native kernel
See µSockets for an up-to-date list of flags and a more detailed explanation.
:handshake: Permissively licensed
Intellectual property, all rights reserved.
Where such explicit notice is given, source code is licensed Apache License 2.0 which is a permissive OSI-approved license with very few limitations. Modified "forks" should be of nothing but licensed source code, and be made available under another product name. If you're uncertain about any of this, please ask before assuming.
Top Related Projects
Tiny WebSocket library for Go.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot