This tutorial demonstrates how Mongoose Library can be used to implement a Websocket client that does the following:

  • Initiates a Websocket connection to the Websocket echo server
  • Sends a websocket message to the echo server
  • When a response is received, quit

A full source code for this tutorial is at https://github.com/cesanta/mongoose/tree/master/examples/websocket-client

NOTE: this example client does not implement an automatic reconnection functionality. If you require that, take a look at MQTT client tutorial

Build and test

In order to test this client implementation, we need a server. We're going to use the one from Websocket Server tutorial. Assuming we're on a Mac or Linux workstation, start a new terminal and execute the following to build and start the websocket server:

$ git clone https://github.com/cesanta/mongoose
$ cd mongoose/examples/websocket-server
$ make
cc ../../mongoose.c -I../.. -W -Wall -DMG_ENABLE_LINES=1  -o example main.c
Starting WS listener on ws://localhost:8000/websocket

Now we have a Websocket echo server up and running on port 8000. Start another terminal, and execute:

$ cd mongoose/examples/websocket-client
$ make
cc ../../mongoose.c -I../.. -W -Wall  -o example main.c
2021-11-17 18:36:11 2 mongoose.c:2487:mg_mgr_fre All connections closed

That's it! We see that a websocket client got an response message and quit.

How it works

A Websocket client is basically a regular HTTP client that sends an HTTP request with a few special headers that initiate Websocket negotiation:

GET /some/uri HTTP/1.1
Host: some.host.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: ....

When a negotiation is complete, a MG_EV_WS_OPEN event is sent. Then a connection becomes a full-duplex connection that receives MG_EV_WS_MSG events for every message from its peer.

Mongoose provides mg_ws_connect API function that performs Websocket negotiation under the hood:

In the event handler function, we catch MG_EV_WS_OPEN - that's when we have established a WS connection. There, we send a message to the server:

When a response message arrives, we catch MG_EV_WS_MSG event, and print a received message:

And this snippet in the event handler function makes our client to exit - on any error, or when any message is received: