As web applications become more sophisticated, WebSocket is becoming more and more popular. It provides a way of building responsive and low-latency web applications by providing a persistent bidirectional communication channel between the client (usually a web browser) and the server. After initial handshake, each frame carries only a small header which reduces overhead compared to plain HTTP, and most importantly, it allows for server-initiated push of the data as it becomes available rather than have the client actively poll the server.
Mongoose Embedded Web Server can be both, Embedded WebSocket Server and Client. We’ll walk through the example here and you can get the code for both examples directly on GitHub (click on the links below).
Our chat server is implemented in the websocket_chat example. WebSocket is an upgrade of an HTTP connection and on the server side both are enabled together by calling mg_set_protocol_http_websocket on the listener connection.
When client successfully upgrades to the WebSocket protocol, Mongoose emits the MG_EV_WEBSOCKET_HANDSHAKE_DONE event. Our server handles it and sends a notice to all connected clients that a new chat participant has joined. From then on, each incoming frame produces a MG_EV_WEBSOCKET_FRAME event, which our chat server handles by broadcasting the message to all the other clients.
The client is implemented in websocket_chat_client. For the client, we create a connection by calling mg_connect_ws. It also contains the code that reads the input from the console which complicates it a bit, but other than that, it should be pretty straightforward. Notice, how the same event types are used for both client and server.