WebSockets are designed to be implemented in web browsers and servers and can be used by any client or server application. As web applications become more sophisticated, WebSocket is gaining popularity. It provides a way of building responsive and low-latency web applications by providing a persistent bidirectional communication channel between the client and the server in real-time. It’s an independent TCP-based protocol and a standardised way for a server to send content without being solicited by the client first. The connection between both can remain open.
Like HTTP, WebSocket is one of the most popular protocols in the world. However, unlike HTTP, WebSocket provides full-duplex communication. This means that after the 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. This is often easier and less resource-intensive than using one channel for reporting and a second for controlling the device. Especially with increasing complexity of the control and reporting logic, the benefits of a bi-directional connection appear.
There are several ways to use WebSocket in Mongoose.
For an embedded WebSocket client use mg_connect_ws (instead of simple mg_connect). This function returns a WebSocket connection.
For an embedded WebSocket server use call mg_set_protocol_http_websocket for the listening connection. And, once the client has sent the protocol upgrade request, the accepted connection becomes a WebSocket connection and its handler will start to receive WebSocket specific events, beginning from MG_EV_WEBSOCKET_HANDSHAKE_REQUEST/MG_EV_WEBSOCKET_HANDSHAKE_DONE.
You can also use the Mongoose WebSocket API, for example mg_send_websocket_frame.
In our examples, you’ll see the simplicity behind this.