Websocket Client
Overview
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, quitf429zi
A full source code for this tutorial is at examples/websocket-client
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.
Follow the Build Tools to setup your development environment. Then start command prompt / terminal, clone Mongoose repository and build the server:
git clone https://github.com/cesanta/mongoose
cd mongoose/examples/websocket-server
make
...
Starting WS listener on ws://localhost:8000/websocket
Now we have a Websocket echo server up and running on port 8000. Start another command prompt / terminal, and execute:
cd mongoose/examples/websocket-client
make
...
GOT ECHO REPLY: [hello]
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:
Done!
NOTE: this example client does not implement an automatic reconnection functionality. If you require that, take a look at MQTT client tutorial