Arduino library · Network

WebSockets by Markus Sattler: a WebSocket client on the ESP32

Yes, with limits. You can use the WebSockets library online in Mokxi with nothing to install, and the sketch runs in your browser. Part of it is not simulated, and the notes below say which. The example below, "The library’s WebSocketClient example, against the simulated echo server", runs on the ESP32 DevKit V1.

Built in on Mokxi: #include <WebSocketsClient.h> and it builds, with nothing to install. Free, and no account needed.

What WebSockets does

The WebSockets library, called arduinoWebSockets in most tutorials, gives an ESP32 or ESP8266 a WebSocket client and a WebSocket server. A WebSocket opens as an ordinary HTTP request and then stays open, so either end can push a message at any moment. That is why it turns up in live dashboards, chat relays and sketches that stream readings to a Node.js or Python server.

Everything arrives through one event function. You call begin() with the host, port and path, hand your handler to onEvent(), and keep calling webSocket.loop(). The handler gets a WStype_t saying what happened (WStype_CONNECTED, WStype_TEXT, WStype_BIN, WStype_DISCONNECTED and a few more), a pointer to the payload and its length. sendTXT() sends text and sendBIN() sends raw bytes.

On this page the example is the library’s own WebSocketClient sketch pointed at echo.mokxi, a simulated echo server. It is not a socket on a wire: the simulated network carries HTTP only, so every message travels as one HTTP POST you can watch in the Cloud panel, and the echo comes back through loop(). Other hosts and beginSSL() never connect, and WebSocketsServer compiles but no browser can reach it.

Library Manager nameWebSockets
AuthorMarkus Sattler
Include#include <WebSocketsClient.h>
#include <WebSocketsServer.h>
#include <WebSockets.h>
BoardsESP32-C3, ESP32-C6, Seeed XIAO ESP32-C3, ESP32-C3 SuperMini, Seeed XIAO ESP32-C6, ESP32 DevKit, ESP32-DevKitC V4, LOLIN32 Lite, Wemos D1 R32, Cheap Yellow Display, TTGO T-Display, ESP32-S3-DevKitC-1, Seeed XIAO ESP32-S3, Arduino Nano ESP32, ESP8266 NodeMCU, Raspberry Pi Pico W, Arduino Uno R4 WiFi
In the simulatorRuns, with a gap the note below names.

Install it

It builds on ESP32-C3, ESP32-C6, Seeed XIAO ESP32-C3, ESP32-C3 SuperMini, Seeed XIAO ESP32-C6, ESP32 DevKit, ESP32-DevKitC V4, LOLIN32 Lite, Wemos D1 R32, Cheap Yellow Display, TTGO T-Display, ESP32-S3-DevKitC-1, Seeed XIAO ESP32-S3, Arduino Nano ESP32, ESP8266 NodeMCU, Raspberry Pi Pico W, Arduino Uno R4 WiFi.

In Mokxi it is built in: #include <WebSocketsClient.h> and the sketch compiles, with no download, no zip and no Library Manager.

On a real board, install "WebSockets" by Markus Sattler from the Arduino IDE’s Library Manager (Sketch, Include Library, Manage Libraries), or add WebSockets to lib_deps in PlatformIO. Mokxi follows the calls of release 2.7.2, so a sketch written here builds there too.

What to know in the simulator: Not a WebSocket on a wire: the simulated network carries HTTP requests and no raw TCP. To echo.mokxi each message is one HTTP POST, in the Cloud panel’s log, and the echoed body comes back from loop(). Any other host, and beginSSL(), never connect: loop() reports WStype_DISCONNECTED and the serial monitor says why. No client can connect to WebSocketsServer, since the Web panel runs no scripts.

The calls you will use

In the order a sketch meets them.

WebSocketsClient webSocket

Declares the client, one object per connection, as a global so loop() and the handler can both reach it.

webSocket.begin("echo.mokxi", 80, "/")

Sets the server’s host, port and path for a plain ws:// connection. Nothing is opened until the first loop().

webSocket.beginSSL("example.com", 443, "/")

The wss:// form, for servers behind TLS. It compiles in Mokxi but never connects, since the simulated network has no TLS sockets.

webSocket.onEvent(webSocketEvent)

Registers the handler that every connect, disconnect and message goes through. Switch on the type.

void webSocketEvent(WStype_t type, uint8_t *payload, size_t length) {
  if (type == WStype_CONNECTED) webSocket.sendTXT("hello");
  if (type == WStype_TEXT) Serial.printf("got %s\n", payload);
}

webSocket.loop()

Runs the connection: opens it, reads frames, answers pings and calls your handler. It must run on every pass of loop().

webSocket.sendTXT("temp=21.5")

Sends a text message and returns true when it went out. Send from the WStype_CONNECTED case or after checking isConnected().

webSocket.sendBIN(buffer, length)

Sends raw bytes, such as a struct of sensor values. The other end receives them as a binary frame.

webSocket.setReconnectInterval(5000)

How long to wait before trying again after a failed or dropped connection, in milliseconds.

webSocket.enableHeartbeat(15000, 3000, 2)

Sends a ping every 15 seconds and drops the connection after two pongs fail to arrive within 3 seconds, so a dead link is noticed.

Example: The library’s WebSocketClient example, against the simulated echo server

On the ESP32 DevKit V1. It runs in the browser exactly as printed.

sketch.ino · ESP32 DevKit V1
#include <Arduino.h>

#include <WiFi.h>
#include <WiFiMulti.h>
#include <WiFiClientSecure.h>

#include <WebSocketsClient.h>

WiFiMulti WiFiMulti;
WebSocketsClient webSocket;

#define USE_SERIAL Serial

void hexdump(const void *mem, uint32_t len, uint8_t cols = 16) {
	const uint8_t* src = (const uint8_t*) mem;
	USE_SERIAL.printf("\n[HEXDUMP] Address: 0x%08X len: 0x%X (%d)", (ptrdiff_t)src, len, len);
	for(uint32_t i = 0; i < len; i++) {
		if(i % cols == 0) {
			USE_SERIAL.printf("\n[0x%08X] 0x%08X: ", (ptrdiff_t)src, i);
		}
		USE_SERIAL.printf("%02X ", *src);
		src++;
	}
	USE_SERIAL.printf("\n");
}

void webSocketEvent(WStype_t type, uint8_t * payload, size_t length) {

	switch(type) {
		case WStype_DISCONNECTED:
			USE_SERIAL.printf("[WSc] Disconnected!\n");
			break;
		case WStype_CONNECTED:
			USE_SERIAL.printf("[WSc] Connected to url: %s\n", payload);

			// send message to server when Connected
			webSocket.sendTXT("Connected");
			break;
		case WStype_TEXT:
			USE_SERIAL.printf("[WSc] get text: %s\n", payload);

			// send message to server
			// webSocket.sendTXT("message here");
			break;
		case WStype_BIN:
			USE_SERIAL.printf("[WSc] get binary length: %u\n", length);
			hexdump(payload, length);

			// send data to server
			// webSocket.sendBIN(payload, length);
			break;
		case WStype_ERROR:
		case WStype_FRAGMENT_TEXT_START:
		case WStype_FRAGMENT_BIN_START:
		case WStype_FRAGMENT:
		case WStype_FRAGMENT_FIN:
			break;
		case WStype_PING:
			// pong will be send automatically
			USE_SERIAL.printf("[WSc] get ping\n");
			break;
		case WStype_PONG:
			// answer to a ping we send
			USE_SERIAL.printf("[WSc] get pong\n");
			break;
	}

}

void setup() {
	// USE_SERIAL.begin(921600);
	USE_SERIAL.begin(115200);

	//Serial.setDebugOutput(true);
	USE_SERIAL.setDebugOutput(true);

	USE_SERIAL.println();
	USE_SERIAL.println();
	USE_SERIAL.println();

	for(uint8_t t = 4; t > 0; t--) {
		USE_SERIAL.printf("[SETUP] BOOT WAIT %d...\n", t);
		USE_SERIAL.flush();
		delay(1000);
	}

	WiFiMulti.addAP("Mokxi-Lab", "breadboard");

	//WiFi.disconnect();
	while(WiFiMulti.run() != WL_CONNECTED) {
		delay(100);
	}

	// server address, port and URL
	webSocket.begin("echo.mokxi", 80, "/");

	// event handler
	webSocket.onEvent(webSocketEvent);

	// use HTTP Basic Authorization this is optional remove if not needed
	webSocket.setAuthorization("user", "Password");

	// try ever 5000 again if connection has failed
	webSocket.setReconnectInterval(5000);

}

void loop() {
	webSocket.loop();
}

Open it in the editor, wired and ready to run

Common errors and how to fix them

[WSc] Disconnected! printed every half second

The connection never opens. Check that the host, port and path match the server exactly, and that you used begin() for ws:// and beginSSL() for wss://. In Mokxi only echo.mokxi answers; any other host reports this and the serial monitor says why.

A message sent at the end of setup() never arrives

The socket is not open yet: it opens inside loop(), after setup() has finished. Send your first message from the WStype_CONNECTED case of the handler, or guard later sends with webSocket.isConnected().

'WebsocketsClient' was not declared in this scope

That spelling, with a lowercase s, belongs to a different library, ArduinoWebsockets by Gil Maimon, whose API uses onMessage() and send(). This library’s class is WebSocketsClient, with handler events instead. Pick one library and follow its own examples.

The connection drops after a few seconds of silence

Something in loop() blocks, usually a long delay() or a slow sensor read, so pings go unanswered and the server gives up. Replace delay() with a millis() timer so webSocket.loop() runs constantly, and add enableHeartbeat() to detect real drops.

Questions and answers

Can a browser page connect to WebSocketsServer on my board in Mokxi?

No. WebSocketsServer compiles and starts, but the Web panel runs no scripts, so nothing can open a socket to it. Test the server side on a real board, and use the client against echo.mokxi here.

Do I need ESPAsyncWebServer for WebSockets?

No. This library runs its own client and server. ESPAsyncWebServer has a separate AsyncWebSocket class that shares the web server’s port, which suits a page and its socket served from one place.

Try WebSockets without installing anything

Open the example, change the sketch, and keep your version in a free account.