ESP32 S3 - WebSocket

WebSocket enables real-time, two-way communication between a web browser and a device like the ESP32 S3 — without ever reloading the page. In this tutorial, we will learn what WebSocket is, why it is ideal for smooth ESP32 S3 control and monitoring, and how to set it up with a practical chat application example.

What you'll build:

  1. A WebSocket server running on the ESP32 S3.
  2. A web page served by the ESP32 S3 that connects to the WebSocket server.
  3. A chat interface that lets you type a message in the browser and send it to the ESP32 S3.
  4. Real-time message replies from the ESP32 S3 displayed in the browser without page reloads.
ESP32 S3 WebSocket - real-time two-way chat between a web browser and the ESP32 S3

Hardware Preparation

1×ESP32 S3 WROOM N16R8
1×Alternatively, ESP32 S3 SuperMini Dev Module
1×Alternatively, ESP32 S3 Uno-form Board
1×Alternatively, ESP32 S3 Camera Board
1×USB Cable Type-A to Type-C (for USB-A PC)
1×USB Cable Type-C to Type-C (for USB-C PC)
1×Recommended: Screw Terminal Expansion Board for ESP32 S3
1×Recommended: Breakout Expansion Board for ESP32 S3
1×Recommended: Power Splitter for ESP32 S3

Or you can buy the following kits:

1×DIYables ESP32 S3 Starter Kit (ESP32 S3 included)
1×DIYables Sensor Kit (18 sensors/displays)
Disclosure: Some of the links provided in this section are Amazon affiliate links. We may receive a commission for any purchases made through these links at no additional cost to you.
Additionally, some of these links are for products from our own brand, DIYables .

What is ESP32 S3 Websocket?

WebSocket is a technology that lets a web browser communicate directly with a web server in real-time, keeping a persistent connection open so data can flow in both directions at any moment. Without WebSocket, the browser must repeatedly refresh or poll the server to receive updates, which is slow and inefficient. With WebSocket, the ESP32 S3 and the browser stay connected continuously, enabling instant data exchange without page reloads — exactly the kind of responsiveness needed for control and monitoring projects.

Key Specifications

  • Protocol: Full-duplex TCP-based WebSocket (RFC 6455)
  • Direction: Browser-to-ESP32 S3 and ESP32 S3-to-browser simultaneously
  • Latency: Near-instant; no page reload required
  • Common use cases: Online games, instant messaging, live dashboards, IoT control panels

Why we need WebSocket to smoothly control ESP32 S3?

Imagine controlling a remote-controlled device using a web interface on your phone. Without WebSocket, every direction or speed change requires a page refresh — like pressing a "reload" button before each command reaches the device. With WebSocket, you have a continuous, direct connection between the browser and the ESP32 S3, so commands arrive instantly with no delay caused by reloading.

In general, WebSocket allows you to:

  • Send data from the web browser to ESP32 S3 without reloading the webpage.
  • Send data from ESP32 S3 to the web browser without reloading the webpage.

This enables true two-way communication in real-time.

Benefits of WebSocket with ESP32 S3:

  • Real-Time Control: WebSocket enables instant communication with the ESP32 S3, ensuring quick responses to commands for a seamless user experience.
  • Persistent Connection: Maintain a continuous link without refreshing the control page, creating an always-ready line of communication for immediate instructions.
  • Efficiency: Experience prompt responses without the need for constant page reloading, enhancing overall user enjoyment and efficiency.

Web Chat with ESP32 S3 via WebSocket

The webpage's content (HTML, CSS, JavaScript) are stored separately on an index.h file. So, we will have two code files on Arduino IDE:

  • An .ino file that is ESP32 S3 code, which creates a web server and WebSocket server
  • An .h file, which contains the webpage's content.

Detailed Instructions

  1. New to ESP32 S3? Complete our Getting Started with ESP32 S3 guide first.
  2. Connect the ESP32 S3 board to your PC via a USB Type-C cable.
  3. Open Arduino IDE on your PC.
  4. Select the right ESP32 S3 board (e.g. ESP32S3 Dev Module) and COM port.
  5. Open the Library Manager by clicking on the Library Manager icon on the left navigation bar of Arduino IDE.
  6. Search "DIYables ESP32 WebServer", then find the Web Server library created by DIYables.
  7. Click Install button to install the Web Server library.
ESP32 S3 Web Server library
  1. On Arduino IDE, create a new sketch and give it a name, for example, newbiely.com.ino.
  2. The following code implements the ESP32 S3 WebSocket server — it handles incoming browser connections, receives messages, and sends replies in real time. Copy it and open it with Arduino IDE.
/* * This ESP32 S3 code was developed by newbiely.com * * This ESP32 S3 code is made available for public use without any restriction * * For comprehensive instructions and wiring diagrams, please visit: * https://newbiely.com/tutorials/esp32-s3/esp32-s3-websocket */ /* * This ESP32-S3 code is created by esp32io.com * * This ESP32-S3 code is released in the public domain * * For more detail (instruction and wiring diagram), visit https://esp32io.com/tutorials/esp32-s3-websocket */ #include <DIYables_ESP32_WebServer.h> #include "index.h" // WiFi credentials const char WIFI_SSID[] = "YOUR_WIFI_SSID"; const char WIFI_PASSWORD[] = "YOUR_WIFI_PASSWORD"; // Create web server instance DIYables_ESP32_WebServer server; DIYables_ESP32_WebSocket* webSocket; // Web Page handlers void handleHome(WiFiClient& client, const String& method, const String& request, const QueryParams& params, const String& jsonData) { // HTML_CONTENT from the index.h file server.sendResponse(client, HTML_CONTENT); } // WebSocket event handlers void onWebSocketOpen(net::WebSocket& ws) { Serial.println("New WebSocket connection"); // Send welcome message const char welcome[] = "Connected to ESP32-S3 WebSocket Server!"; } void onWebSocketMessage(net::WebSocket& ws, const net::WebSocket::DataType dataType, const char* message, uint16_t length) { Serial.print("WebSocket Received ("); Serial.print(length); Serial.print(" bytes): "); Serial.println(message); // Broadcast response to all connected clients using the library if (webSocket != nullptr) { String response = "Received: " + String((char*)message); webSocket->broadcastTXT(response); Serial.print("WebSocket sent ("); Serial.print(response.length()); Serial.print(" bytes): "); Serial.println(response); } } void onWebSocketClose(net::WebSocket& ws, const net::WebSocket::CloseCode code, const char* reason, uint16_t length) { Serial.println("WebSocket client disconnected"); } void setup() { Serial.begin(9600); delay(1000); Serial.println("ESP32-S3 Web Server and WebSocket Server"); // Configure web server routes server.addRoute("/", handleHome); // Start web server with WiFi connection server.begin(WIFI_SSID, WIFI_PASSWORD); // Enable WebSocket functionality webSocket = server.enableWebSocket(81); if (webSocket != nullptr) { // Set up WebSocket event handlers webSocket->onOpen(onWebSocketOpen); webSocket->onMessage(onWebSocketMessage); webSocket->onClose(onWebSocketClose); } else { Serial.println("Failed to start WebSocket server"); } } void loop() { // Then handle HTTP requests server.handleClient(); // Handle WebSocket server.handleWebSocket(); }
  1. Modify the WiFi information (SSID and password) in the code to match your own network credentials.
  2. Create the index.h file in Arduino IDE by:
    • Either click on the button just below the serial monitor icon and choose New Tab, or use Ctrl+Shift+N keys.
    Arduino IDE 2 adds file
    • Give the file's name index.h and click OK button.
    Arduino IDE 2 adds file index.h
    • The following code defines the webpage served to the browser, including the chat UI and the JavaScript that manages the WebSocket connection. Copy it and paste it into index.h.
    /* * This ESP32 S3 code was developed by newbiely.com * * This ESP32 S3 code is made available for public use without any restriction * * For comprehensive instructions and wiring diagrams, please visit: * https://newbiely.com/tutorials/esp32-s3/esp32-s3-websocket */ const char *HTML_CONTENT = R"=====( <!DOCTYPE html> <!-- saved from url=(0019)http://192.168.0.2/ --> <html><head><meta http-equiv="Content-Type" content="text/html; charset=windows-1252"> <title>ESP32 WebSocket</title> <meta name="viewport" content="width=device-width, initial-scale=0.7"> <link rel="icon" href="https://diyables.io/images/page/diyables.svg"> <style> /* Add some basic styling for the chat window */ body { font-size: 16px; } .chat-container { width: 400px; margin: 0 auto; padding: 10px; } .chat-messages { height: 250px; overflow-y: auto; border: 1px solid #444; padding: 5px; margin-bottom: 5px; } .user-input { display: flex; margin-bottom: 20px; } .user-input input { flex: 1; border: 1px solid #444; padding: 5px; } .user-input button { margin-left: 5px; background-color: #007bff; color: #fff; border: none; padding: 5px 10px; cursor: pointer; } .websocket { display: flex; align-items: center; margin-bottom: 5px; } .websocket button { background-color: #007bff; color: #fff; border: none; padding: 5px 10px; cursor: pointer; } .websocket .label { margin-left: auto; } </style> <script> var ws; var wsm_max_len = 4096; /* bigger length causes uart0 buffer overflow with low speed smart device */ function update_text(text) { var chat_messages = document.getElementById("chat-messages"); chat_messages.innerHTML += text + '<br>'; chat_messages.scrollTop = chat_messages.scrollHeight; } function send_onclick() { if(ws != null) { var message = document.getElementById("message").value; if (message) { document.getElementById("message").value = ""; ws.send(message + "\n"); update_text('<span style="color:navy">' + message + '</span>'); // You can send the message to the server or process it as needed } } } function connect_onclick() { if(ws == null) { ws = new WebSocket("ws://" + window.location.host + ":81"); document.getElementById("ws_state").innerHTML = "CONNECTING"; ws.onopen = ws_onopen; ws.onclose = ws_onclose; ws.onmessage = ws_onmessage; } else ws.close(); } function ws_onopen() { document.getElementById("ws_state").innerHTML = "<span style='color:blue'>CONNECTED</span>"; document.getElementById("bt_connect").innerHTML = "Disconnect"; document.getElementById("chat-messages").innerHTML = ""; } function ws_onclose() { document.getElementById("ws_state").innerHTML = "<span style='color:gray'>CLOSED</span>"; document.getElementById("bt_connect").innerHTML = "Connect"; ws.onopen = null; ws.onclose = null; ws.onmessage = null; ws = null; } function ws_onmessage(e_msg) { e_msg = e_msg || window.event; // MessageEvent console.log(e_msg.data); update_text('<span style="color:blue">' + e_msg.data + '</span>'); } </script> </head> <body> <div class="chat-container"> <h2>ESP32 WebSocket</h2> <div class="websocket"> <button class="connect-button" id="bt_connect" onclick="connect_onclick()">Connect</button> <span class="label">WebSocket: <span id="ws_state"><span style="color:blue">CLOSED</span></span></span> </div> <div class="chat-messages" id="chat-messages"></div> <div class="user-input"> <input type="text" id="message" placeholder="Type your message..."> <button onclick="send_onclick()">Send</button> </div> <div class="sponsor">Sponsored by <a href="https://amazon.com/diyables">DIYables</a></div> </div> </body></html> )=====";
    1. Now you have the code in two files: newbiely.com.ino and index.h.
    2. Click Upload button on Arduino IDE to upload code to the ESP32 S3.
    3. Open the Serial Monitor and check the output. You should see readings similar to the following (timestamps are for reference):
    ∞
    Newbiely | Arduino IDE 2.3.8
    ──
    ☐
    ✕
    File
    Edit
    Sketch
    Tools
    Help
    ESP32S3 Dev Module
    Newbiely.ino
    ···
    8 Serial.println("Hello World!");
    Output
    Serial Monitor
    Message (Enter to send message to 'ESP32S3 Dev Module' on 'COM15')
    New Line
    9600 baud
    [2026-01-15 09:12:03] Connecting to WiFi... [2026-01-15 09:12:05] Connected to WiFi [2026-01-15 09:12:05] ESP32 S3 Web Server's IP address: 192.168.0.2 [2026-01-15 09:12:11] WebSocket client connected
    Ln 11, Col 1
    ESP32S3 Dev Module on COM15
    2
    1. Take note of the IP address displayed, and enter this address into the address bar of a web browser on your smartphone or PC.
    2. You will see the webpage as below:
    ESP32 S3 websocket web browser
    1. Click the CONNECT button to connect the webpage to ESP32 S3 via WebSocket.
    2. Type some words and send them to ESP32 S3.
    3. You will see the response from ESP32 S3.
    ESP32 S3 websocket chat server
    1. Pro Tip: If you modify only the HTML content in index.h without touching newbiely.com.ino, Arduino IDE may not recompile the HTML. To force an update, make a trivial change in the .ino file (e.g., add a blank line or a comment) before uploading.

    ※ NOTE THAT:

    • If you modify the HTML content in the index.h and does not touch anything in newbiely.com.ino file, when you compile and upload code to ESP32 S3, Arduino IDE will not update the HTML content.
    • To make Arduino IDE update the HTML content in this case, make a change in the newbiely.com.ino file (e.g. adding empty line, add a comment....)

    Line-by-line Code Explanation

    The above ESP32 S3 code contains line-by-line explanation. Please read the comments in the code!

How the System Operates

The ESP32 S3 code functions by creating both a web server and a WebSocket server, allowing the browser and the board to maintain a live, bidirectional channel. The process unfolds as follows:

  • When you input the ESP32 S3's IP address into a web browser, a request is made for the webpage (User Interface) from the ESP32 S3.
  • The ESP32 S3's web server responds by transmitting the content of the webpage (HTML, CSS, JavaScript).
  • Subsequently, your web browser displays the webpage.
  • When you click the CONNECT button, the JavaScript code embedded in the webpage establishes a WebSocket connection to the WebSocket server on the ESP32 S3.
  • With the WebSocket connection established, when you type something and click the SEND button, the JavaScript code sends that text to the ESP32 S3 through the WebSocket connection in the background.
  • Upon receiving the message, the WebSocket server sends back a reply to the webpage.

Real-World Applications

WebSocket is the foundation for a wide range of interactive ESP32 S3 projects that demand low-latency, continuous communication between the board and a browser-based interface.

  1. Remote Robot Control: Send movement commands to a robot car from the browser and receive live sensor feedback without any page refresh.
  2. Live Sensor Dashboard: Stream temperature, humidity, or motion data from the ESP32 S3 to a browser chart that updates in real time.
  3. Smart Home Panel: Control lights, fans, and relays from a single web page with instant on/off feedback.
  4. Industrial Monitor: Display machine status, error alerts, and counters from factory equipment connected to the ESP32 S3.
  5. Multiplayer IoT Games: Coordinate multiple ESP32 S3 devices through a shared WebSocket server for synchronized interactive experiences.

Video Tutorial

Watch the step-by-step video walkthrough for this ESP32 S3 project below.

Challenges

Once you have the basic WebSocket chat working, try pushing it further with these extension challenges. Each one reinforces a different aspect of real-time web communication with the ESP32 S3.

  1. Beginner: Add a button on the webpage that sends a fixed command string (e.g., "LED_ON") to the ESP32 S3 and have the board echo it back with a confirmation message.
  2. Intermediate: Modify the ESP32 S3 sketch to broadcast a counter value to all connected WebSocket clients every second, and display it as a live number on the webpage.
  3. Advanced: Implement a password-protected WebSocket connection — the browser must send a secret token as the first message, and the ESP32 S3 closes the connection if the token is wrong.

You can learn other ESP32 S3 WebSocket examples below:

※ OUR MESSAGES

  • As freelancers, We are AVAILABLE for HIRE. See how to outsource your project to us
  • Please feel free to share the link of this tutorial. However, Please do not use our content on any other websites. We invested a lot of effort and time to create the content, please respect our work!