WEBSOCKET CLIENT AND SERVER

What is WebSocket?

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.

Why is WebSocket important for connectivity?

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.

WebSocket and Mongoose Embedded Web Server

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 addition, Mongoose provides a lot of helpers, for example, for parsing HTTP headers, serving files, parsing and composing addresses.

WebSocket server example

Create listening connection:

struct mg_connection *c = mg_bind(&mgr, "8080", ev_handler);
mg_set_protocol_http_websocket(c);

An handle WebSocket events:

void ev_handler(struct mg_connection *c, int ev, void *ev_data) {
  struct websocket_message *wm = (struct websocket_message *) ev_data;
  switch (ev) {
    case MG_EV_WEBSOCKET_FRAME:
      /* Echo received frame back */
      mg_send_websocket_frame(c, WEBSOCKET_OP_TEXT, wm->data, wm->size);
      break;
    ...

WebSocket client example

Make a connection:

mg_connect_ws(&mgr, ev_handler, url, "my_app", NULL);

Then handle frames the same way as server code does.

Full list of examples

SEE ALL EXAMPLES DOWNLOAD SOURCE CODE