Language: C
Networking / WebSocket
libwebsockets was created by Andy Green to provide a fast, lightweight, and flexible WebSocket library in C. It is widely used in IoT, embedded systems, and web applications where low-level, high-performance WebSocket support is required.
libwebsockets is a lightweight C library for building WebSocket servers, clients, and HTTP(S) servers. It supports asynchronous, event-driven communication over WebSocket and HTTP protocols.
sudo apt install libwebsockets-devbrew install libwebsocketsBuild from source: https://libwebsockets.orglibwebsockets provides APIs for creating WebSocket clients and servers, handling events like connections, messages, and disconnections, and integrating with HTTP and SSL/TLS for secure communication.
#include <libwebsockets.h>
#include <string.h>
#include <signal.h>
static int interrupted = 0;
static int callback_echo(struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len) {
switch (reason) {
case LWS_CALLBACK_RECEIVE:
lws_write(wsi, (unsigned char *)in, len, LWS_WRITE_TEXT);
break;
default:
break;
}
return 0;
}
int main() {
struct lws_context_creation_info info;
memset(&info, 0, sizeof(info));
struct lws_protocols protocols[] = {
{ "echo-protocol", callback_echo, 0, 1024, },
{ NULL, NULL, 0, 0 }
};
info.port = 8080;
info.protocols = protocols;
struct lws_context *context = lws_create_context(&info);
while (!interrupted) {
lws_service(context, 1000);
}
lws_context_destroy(context);
return 0;
}Sets up a simple WebSocket echo server on port 8080 using libwebsockets.
// Client code involves creating context, connecting to server using lws_client_connect_via_info,
// and handling events like LWS_CALLBACK_CLIENT_RECEIVE.// Configure SSL options in lws_context_creation_info for secure WebSocket connections using certificates.// Define multiple lws_protocols with different callbacks and attach them to the context.// Use lws_callback_on_writable() to schedule asynchronous writes without blocking the event loop.Use the event-driven API for non-blocking communication.
Handle all WebSocket and HTTP events in callbacks to maintain responsiveness.
Use SSL/TLS for secure connections where needed.
Predefine protocols to organize multiple types of WebSocket messages.
Clean up the context and connections properly to avoid memory leaks.