ESP32 WebSocket enables full-duplex, low-latency communication between an ESP32 microcontroller and a remote client or server over Wi-Fi. Unlike HTTP polling, WebSocket maintains a persistent connection, making it ideal for real-time sensor streaming and remote GPIO control. VideoSDK extends similar real-time capabilities to IoT devices through its multi-platform SDK support.
Real-time bidirectional communication is the backbone of modern IoT projects. Whether you are streaming temperature readings from a remote sensor or toggling a relay from a web dashboard, the ability to push data instantly in both directions without repeated HTTP requests changes how you design embedded systems. The ESP32, with its built-in Wi-Fi radio and dual-core processing, is one of the most popular microcontrollers for connected projects. Pairing it with the WebSocket protocol gives you a lightweight, persistent channel that avoids the overhead and latency of HTTP polling.
By the end of this guide, you will understand how the WebSocket protocol works on the ESP32, how to set up both an ESP32 WebSocket client and server using ESP-IDF, how to secure your connections with TLS, and how to troubleshoot the most common issues developers encounter in production.

What Is a WebSocket and How Does It Work on ESP32?

WebSocket is a communication protocol that provides full-duplex, persistent communication over a single TCP connection. It is defined in RFC 6455 and is designed to overcome the limitations of HTTP for real-time applications. Unlike HTTP, which follows a request-response pattern where the client must initiate every exchange, WebSocket allows either side to send data at any time after the initial connection is established.
The protocol begins with an HTTP handshake. The client sends an HTTP GET request with an Upgrade header, asking the server to switch protocols. If the server supports WebSocket, it responds with a 101 Switching Protocols status code. From that point on, the connection is no longer HTTP. It becomes a raw TCP channel where both sides can exchange framed messages independently.
This full-duplex behavior is what makes WebSocket on ESP32 so powerful for IoT. A sensor can push readings to a dashboard the moment they are available, and a user can send a control command back through the same connection without opening a new request. The overhead per message is minimal compared to HTTP, which matters when you are working with the ESP32's limited memory and bandwidth.
On the ESP32, the WebSocket protocol is supported natively through the ESP-IDF framework. The ESP-IDF provides both client and server components that handle the handshake, frame encoding, and event dispatching for you. According to the official ESP-IDF documentation, the framework handles the protocol-level details so you can focus on your application logic.
The diagram below illustrates the handshake and data exchange flow between a browser client and an ESP32 WebSocket endpoint:

ESP32 WebSocket Client Overview

The ESP32 WebSocket client component in ESP-IDF lets your microcontroller initiate outbound WebSocket connections to remote servers, cloud platforms, or local dashboards. This is the mode you use when the ESP32 is acting as a sensor node reporting data upstream or receiving configuration commands from a central service.
The client component supports TCP connections, TLS-secured connections using the secure WebSocket scheme, and multiple simultaneous WebSocket instances. This means a single ESP32 can maintain separate connections to different endpoints at the same time, which is useful for edge gateway designs that aggregate data from local sensors and forward it to multiple cloud services.
Key configuration fields include the WebSocket URI, which specifies the scheme, host, port, and path. For secure connections, you provide a PEM-encoded server certificate that the client uses to verify the server's identity. You can also specify a WebSocket sub-protocol, which is useful when connecting to services that expect a specific protocol identifier in the handshake headers.
Typical use cases for the ESP32 WebSocket client include connecting to cloud dashboards for real-time sensor visualization, receiving remote commands to control GPIO pins or actuators, and bridging local serial data to a remote processing service. Developers building more advanced real-time IoT applications that require audio or video streaming from edge devices can also explore VideoSDK's IoT SDK, which extends real-time communication capabilities to embedded platforms.
The component diagram below shows how the ESP32 WebSocket client fits into a typical IoT architecture:

Setting Up the Client

Setting up an ESP32 WebSocket client begins with including the WebSocket client component in your ESP-IDF project. You add the component dependency to your project configuration, then initialize the client with your desired parameters.
The first decision is whether to use unencrypted or encrypted WebSocket URIs. The unencrypted scheme uses plain TCP and is suitable for local development or LAN-only communication where security is not a concern. The encrypted scheme adds TLS encryption and should be used for any connection that traverses the public internet or carries sensitive data.
For TLS connections, you need to obtain the server's PEM certificate. This is typically the CA certificate that signed the server's TLS certificate. You embed this certificate as a string constant in your firmware or load it from a partition. The certificate must match the one presented by the server during the TLS handshake, or the connection will fail.
Common pitfalls at this stage include mismatched port numbers, using the wrong certificate format, and forgetting to enable the WebSocket component in your build configuration. Another frequent issue is attempting to connect to an encrypted WebSocket endpoint without providing a valid certificate, which results in a handshake failure that can be difficult to diagnose without checking the ESP-IDF log output.

Managing Client Events

The ESP32 WebSocket client uses an event-driven model. When the client connects, disconnects, or receives data, it triggers events that your application handles through registered callback functions. This design keeps your main loop free from blocking network calls and lets you respond to network state changes asynchronously.
The primary event types include connection events, which fire when the WebSocket handshake completes successfully, disconnection events, which fire when the connection drops or is closed by the server, and data events, which fire whenever a complete WebSocket frame is received.
For handling fragmented frames, the client component reassembles fragmented messages automatically in most configurations. However, if you are working with very large payloads, you should be aware of the ESP32's memory constraints and consider chunking your data into smaller messages. Ping and pong frames are handled internally by the component to maintain the connection, but you can configure custom keep-alive intervals to match your network conditions.

ESP32 WebSocket Server Overview

Running a WebSocket server directly on the ESP32 is useful when you want the microcontroller to act as a self-contained endpoint that local clients can connect to. This is common in home automation projects, local dashboards, and LAN-based control systems where the ESP32 does not need to depend on an external cloud service.
The ESP-IDF WebSocket server component supports multiple simultaneous client connections, message broadcasting to all connected clients, and custom event handlers for different URI paths. You can serve both WebSocket upgrade requests and static HTTP content from the same ESP32, which means a single device can host the web interface and the real-time communication channel.
Security options for the server include plain TCP for LAN-only deployments and TLS for encrypted communication. The server can also be configured to require client certificate verification for mutual TLS, which ensures that only trusted devices can connect.
The architecture diagram below shows an ESP32 WebSocket server handling multiple browser clients with an optional TLS layer:
Architecture Diagram

Building a Simple Server

Creating an ESP32 WebSocket server involves initializing the server component, binding it to a network port, and registering URI handlers that accept WebSocket upgrade requests. The ESP-IDF HTTP server component integrates with the WebSocket server, so you can serve static files like HTML and JavaScript from one URI path while accepting WebSocket connections on another.
The typical workflow starts with configuring the HTTP server with your desired port and security settings. You then register a WebSocket handler for a specific URI path, such as the root path or a dedicated endpoint. When a client sends an HTTP upgrade request to that path, the server performs the WebSocket handshake and transitions the connection to the WebSocket protocol.
To serve static content alongside the WebSocket endpoint, you register additional HTTP handlers that respond to GET requests with your HTML, CSS, and JavaScript files. These files can be embedded in the firmware using the ESP-IDF SPIFFS or embedded data components, or served from an SD card if your project includes one.
Scaling to several simultaneous connections requires careful memory management. Each WebSocket connection consumes RAM for its receive buffer and connection state. The ESP32 has approximately 520 KB of SRAM, so you should limit the number of concurrent connections based on your buffer sizes and available heap memory. A practical recommendation is to keep concurrent connections under ten for typical sensor dashboard applications.

Broadcasting Sensor Data

A common pattern for ESP32 WebSocket servers is reading sensor data and pushing it to all connected clients in real time. For example, if you have a BME280 temperature and humidity sensor connected to your ESP32 via I2C, you can read the sensor at a fixed interval and broadcast the values to every connected WebSocket client.
The broadcast mechanism sends the same message to all active connections registered with the server. You format the sensor data as a text frame, typically using a JSON structure that the client-side JavaScript can parse directly. The server iterates through all connected clients and sends the payload through each active WebSocket.
Managing update intervals is critical to avoid saturating the ESP32's Wi-Fi bandwidth and running out of memory. For most environmental sensors, an update every one to five seconds is sufficient. Faster update rates are possible but require smaller payloads and careful monitoring of heap memory. If you have multiple sensors, consider interleaving their broadcasts rather than sending all values in a single large message.

Security Best Practices for ESP32 WebSocket

Security is often an afterthought in IoT projects, but it should be part of your design from the start. WebSocket connections that traverse the public internet without encryption expose your data and your device to interception and tampering.
Use the encrypted WebSocket scheme for any WebSocket connection that leaves your local network. This encrypts the communication channel using TLS, protecting both the handshake and the subsequent data frames. To enable TLS on the ESP32, you embed the server's PEM certificate in your firmware. The ESP32's hardware acceleration for TLS operations helps reduce the CPU overhead of encryption, but you should still expect higher latency compared to plain TCP connections.
For scenarios where you need to verify the identity of the client as well as the server, ESP-IDF provides the ESP-Secure-Cert-Mgr component. This enables mutual TLS, where both sides present and validate certificates. Mutual TLS is particularly valuable in industrial IoT settings where you need to ensure that only authorized devices can connect to your infrastructure.
Beyond TLS, you should implement application-level security measures. IP filtering restricts connections to known addresses, which is useful for LAN deployments with a fixed set of clients. Token validation adds an authentication layer where clients must present a valid token in the initial WebSocket handshake or in the first message after connection. This prevents unauthorized clients from sending commands to your ESP32 even if they reach the network.
For developers building production IoT systems that need scalable, secure real-time communication, VideoSDK's platform offers built-in encryption, token-based authentication, and room-based access control that can complement or replace custom WebSocket implementations as your project grows.

Debugging and Performance Tips

Debugging WebSocket issues on the ESP32 requires a systematic approach because errors can originate from the network layer, the TLS layer, or the WebSocket protocol layer itself.
One of the most common error messages is a failed handshake. This typically means the server rejected the upgrade request, which can happen if the URI path is incorrect, the server does not support WebSocket, or the server expects a specific sub-protocol that the client did not specify. Check the ESP-IDF log output for the exact HTTP status code returned by the server.
Certificate mismatch errors occur when the PEM certificate embedded in your firmware does not match the certificate presented by the server. This can happen if the server's certificate has been renewed or if you are using the wrong CA certificate. Verify that you are using the root CA certificate, not the server's leaf certificate, and that the certificate is in PEM format with proper header and footer lines.
ESP-IDF provides detailed logging through the esp_log component. Enable verbose logging for the WebSocket and TLS components during development to see the handshake details, frame sizes, and error codes. Wi-Fi diagnostics are also available through the ESP-IDF monitoring tools, which show connection status, signal strength, and disconnection reasons.
For performance optimization, consider the payload size carefully. Text frames are convenient because they can carry JSON directly, but binary frames are more compact for numeric data. If you are streaming raw sensor values, packing them into a binary frame can reduce bandwidth usage significantly. Keep-alive intervals should be tuned to your network conditions. A keep-alive interval that is too short wastes bandwidth, while one that is too long may allow dead connections to persist and consume memory.

Real-World Example Scenarios

ESP32 WebSocket projects span a wide range of real-world applications. A remote sensor dashboard for home automation is one of the most common. The ESP32 reads data from environmental sensors and serves a web page to browsers on the local network. A WebSocket connection pushes sensor updates to the dashboard in real time, giving users a live view of temperature, humidity, and air quality without refreshing the page.
Live GPIO control from a web page is another popular scenario. The ESP32 hosts a WebSocket server that accepts commands from a browser interface. When a user clicks a button on the web page, the browser sends a WebSocket message to the ESP32, which toggles the corresponding GPIO pin. This pattern is used in smart switches, relay controllers, and robotic actuator interfaces.
An edge gateway design uses the ESP32 as both a WebSocket server and a WebSocket client simultaneously. The ESP32 accepts connections from local sensors or other ESP32 devices, aggregates the data, and forwards it to a cloud WebSocket service. This architecture is common in industrial IoT deployments where multiple sensor nodes report to a gateway that manages the upstream cloud connection. For projects that need to scale beyond simple WebSocket messaging to full real-time audio or video communication from edge devices, VideoSDK's IoT SDK provides a path to production-grade real-time communication.

Definitions Glossary

WebSocket: A communication protocol providing full-duplex, persistent communication over a single TCP connection, defined in RFC 6455. On the ESP32, WebSocket enables real-time bidirectional data exchange without the overhead of repeated HTTP requests.
ESP-IDF: The official development framework for ESP32 microcontrollers, providing components for Wi-Fi, WebSocket client and server, TLS, and hardware peripherals. It includes native WebSocket support through dedicated protocol components.
WebSocket Handshake: The initial HTTP exchange where a client sends an Upgrade header and the server responds with a 101 Switching Protocols status, transitioning the connection from HTTP to WebSocket. This handshake is handled automatically by the ESP-IDF WebSocket components.
TLS (Transport Layer Security): A cryptographic protocol that encrypts data sent over a network connection. On the ESP32, TLS secures WebSocket connections using the encrypted WebSocket scheme and is accelerated by the chip's hardware cryptographic engine.
Full-Duplex Communication: A communication mode where both parties can send and receive data simultaneously over the same connection. WebSocket provides full-duplex communication, which is essential for real-time IoT applications like sensor streaming and remote control.
WebSocket Frame: The basic unit of data exchange in the WebSocket protocol, which can carry text or binary data. The ESP32 WebSocket components handle frame encoding and decoding automatically, including fragmentation and reassembly for large messages.

Key Takeaways

  • ESP32 WebSocket provides full-duplex, low-latency communication that eliminates the need for HTTP polling in real-time IoT applications.
  • The ESP-IDF framework includes both WebSocket client and server components, supporting TLS encryption, multiple connections, and event-driven programming.
  • Security should be designed in from the start, using encrypted WebSocket connections for encrypted communication, mutual TLS for device authentication, and application-level token validation for access control.
  • Performance optimization on the ESP32 requires careful attention to payload size, binary versus text frames, keep-alive intervals, and heap memory monitoring.
  • Developers scaling IoT projects beyond simple WebSocket messaging can explore VideoSDK's multi-platform SDK support, including IoT integration for production-grade real-time communication.

Conclusion

ESP32 WebSocket is a powerful combination for any IoT project that needs low-latency, bidirectional communication. Whether you are building a local sensor dashboard with the ESP32 acting as a WebSocket server or connecting your device to a cloud platform as a WebSocket client, the ESP-IDF framework gives you the tools to implement both modes with TLS security and event-driven architecture. Start with a simple client or server setup, add TLS once your basic communication works, and iterate on your payload format and update intervals based on your specific sensor and bandwidth requirements. For developers ready to explore beyond raw WebSocket handling, VideoSDK's documentation offers a path to production-grade real-time communication across ten or more platforms, including IoT devices. You can sign up for free at app.videosdk.live/login to explore the platform. What are you building with ESP32 WebSocket? Drop a comment and share your IoT project ideas with the community.

Free $20 Balance for AI Voice Agents & Video Calls

FAQ