Beginning Guide to Websocket with NodeMCU

in this tutorial, I will show you Beginning Guide to Websocket with NodeMCU Step by step complete project.

Web Socket is a computer communications protocol, giving full-duplex communication channels over a single TCP connection. The Web Socket protocol was standardized by the IETF as RFC 6455 in 2011, and the Web Socket API in Web IDL is being standardized by the W3C.

≡ Required Component :

Here is a list of the hardware we suggest Beginning Guide to Websocket with NodeMCU

  1. NodeMcu8266
  2. Breadboard
  3. Connecting wire
  4. Breadboard Power Supply Module

≡ What is WebSocket?

WebSocket allows bidirectional communication in real-time over the web. WebSocket can be run together with a standard HTTP server. simply You can click a button in a web browser, and enable a GPIO on your NodeMCU which turns on a light in your house. All in real-time, and with communication going both ways!

in this tutorial, we will set up a web server with WebSocket. Then build a browser UI to interact with NodeMCU, here for simplicity we send plain text messages to ESP266 and get feedback on the same text message. To create real applications use JSON to make an easy separation between multiple data fields like LED on-off, ADC value, etc.

at one time you get a Web Socket connection with the webserver, you can transmit data from browser to server by calling a send() method, and receive data from server to browser by an onmessage event handler.

Following is the API which builds a new WebSocket object.

var Socket = new WebSocket(url, [protocol] );

Here first argument, URL, specifies the URL to which to attach. The second attribute, protocol is optional. and if present, names a sub-protocol that the server must support for the link to be successful.

≡ WebSocket Formula

The following are the formula linked with the WebSocket objects. we created a Socket object as mentioned above −


Method & Description



The send(data) method transmits data using the connection.



The close() method would be used to terminate an existing connection.

≡ WebSocket example

The program created with two separate files, one contains all HTML and Java Code, the second file is NodeMCU code.

HTML and Java Code

const char MAIN_page[] = R"=====(
*, *:before, *:after {
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
html {
  font-family: Helvetica, Arial, sans-serif;
  font-size: 100%;
  background: #333;
#page-wrapper {
  width: 650px;
  background: #FFF;
  padding: 1em;
  margin: 1em auto;
  border-top: 5px solid #69c773;
  box-shadow: 0 2px 10px rgba(0,0,0,0.8);
h1 {
  margin-top: 0;
#status {
  font-size: 0.9rem;
  margin-bottom: 1rem;
.open {
  color: green;
.closed {
  color: red;
ul {
  list-style: none;
  margin: 0;
 padding: 0;
  font-size: 0.95rem;
ul li {
  padding: 0.5rem 0.75rem;
  border-bottom: 1px solid #EEE;
ul li:first-child {
  border-top: 1px solid #EEE;
ul li span {
  display: inline-block;
  width: 90px;
  font-weight: bold;
  color: #999;
  font-size: 0.7rem;
  text-transform: uppercase;
  letter-spacing: 1px;
.sent {
  background-color: #F7F7F7;
.received {}
#message-form {
  margin-top: 1.5rem;
textarea {
  width: 100%;
  padding: 0.5rem;
  font-size: 1rem;
  border: 1px solid #D9D9D9;
  border-radius: 3px;
  box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.1);
  min-height: 100px;
  margin-bottom: 1rem;
button {
  display: inline-block;
  border-radius: 3px;
  border: none;
  font-size: 0.9rem;
  padding: 0.6rem 1em;
  color: white;
  margin: 0 0.25rem;
  text-align: center;
  background: #BABABA;
  border-bottom: 1px solid #999;
button[type="submit"] {
  background: #86b32d;
  border-bottom: 1px solid #5d7d1f;
button:hover {
  opacity: 0.75;
  cursor: pointer;
window.onload = function() {
  // Get references to elements on the page.
  var form = document.getElementById('message-form');
  var messageField = document.getElementById('message');
  var messagesList = document.getElementById('messages');
  var socketStatus = document.getElementById('status');
  var closeBtn = document.getElementById('close');
 // Create a new WebSocket.
  var socket = new WebSocket('ws://' + location.hostname + ':81/', ['arduino']);
  // Handle any errors that occur.
  socket.onerror = function(error) {
    console.log('WebSocket Error: ' + error);
  // Show a connected message when the WebSocket is opened.
  socket.onopen = function(event) {
    socketStatus.innerHTML = 'Connected to: ' + event.currentTarget.url;
    socketStatus.className = 'open';
  // Handle messages sent by the server.
  socket.onmessage = function(event) {
    var message =;
    messagesList.innerHTML += '<li class="received"><span>Received:</span>' + message + '</li>';
  // Show a disconnected message when the WebSocket is closed.
  socket.onclose = function(event) {
    socketStatus.innerHTML = 'Disconnected from WebSocket.';
    socketStatus.className = 'closed';
  // Send a message when the form is submitted.
  form.onsubmit = function(e) {
    // Retrieve the message from the textarea.
    var message = messageField.value;
    // Send the message through the WebSocket.
    // Add the message to the messages list.
    messagesList.innerHTML += '<li class="sent"><span>Sent:</span>' + message + '</li>';
    // Clear out the message field.
    messageField.value = '';
    return false;
  // Close the WebSocket connection when the close button is clicked.
  closeBtn.onclick = function(e) {
    // Close the WebSocket.
    return false;
<div id="page-wrapper">
  <h1>Websocket Communication Example</h1>
  <div id="status"><h1>Connecting...</h1></div>
  <ul id="messages"></ul>
  <form id="message-form" action="#" method="post">
    <textarea id="message" placeholder="Write your message here..." required></textarea>
    <button type="submit">Send Message</button>
    <button type="button" id="close">Close Connection</button>

NodeMCU code:

#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <WebSocketsServer.h>
#include "index.h"  //Web page with client side socket handling script
ESP8266WebServer server(80);       // create a web server on port 80
WebSocketsServer webSocket = WebSocketsServer(81);    // create a websocket server on port 81
const char ssid[] = "Mechatronicslab";
const char pass[] = "Pa$$word";
const char* mdnsName = "esp8266"; // Domain name for the mDNS responder
void setup() {
  Serial.begin(115200);        // Start the Serial communication to send messages to the computer
  startWiFi();                 // Start a Wi-Fi access point, and try to connect to some given access points. Then wait for either an AP or STA connection
  startWebSocket();            // Start a WebSocket server
  startMDNS();                 // Start the mDNS responder
  startServer();               // Start a HTTP server with a file read handler and an upload handler
void startWiFi() { // Start a Wi-Fi access point, and try to connect to some given access points. Then wait for either an AP or STA connection
  WiFi.begin(ssid, pass);
  while (WiFi.status() != WL_CONNECTED) {
void startWebSocket() { // Start a WebSocket server
  webSocket.begin();                          // start the websocket server
  webSocket.onEvent(webSocketEvent);          // if there's an incoming websocket message, go to function 'webSocketEvent'
  Serial.println("WebSocket server started.");
void startMDNS() { // Start the mDNS responder
  MDNS.begin(mdnsName);                        // start the multicast domain name server
  Serial.print("mDNS responder started: http://");
void handleRoot() {
  String s = MAIN_page;
  server.send(200, "text/html", s);
void startServer() { // Start a HTTP server with a file read handler and an upload handler
  server.onNotFound(handleNotFound);          // if someone requests any other file or page, go to function 'handleNotFound'
  server.begin();                             // start the HTTP server
  Serial.println("HTTP server started.");
unsigned long prevMillis = millis();
void loop() {
  webSocket.loop();                           // constantly check for websocket events
  server.handleClient();                      // run the server
void handleNotFound(){ // if the requested file or page doesn't exist, return a 404 not found error
    server.send(404, "text/plain", "404: File Not Found");
void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t lenght) { // When a WebSocket message is received
  switch (type) {
    case WStype_DISCONNECTED:             // if the websocket is disconnected
      Serial.printf("[%u] Disconnected!\n", num);
    case WStype_CONNECTED: {              // if a new websocket connection is established
        IPAddress ip = webSocket.remoteIP(num);
        Serial.printf("[%u] Connected from %d.%d.%d.%d url: %s\n", num, ip[0], ip[1], ip[2], ip[3], payload);
    case WStype_TEXT:                     // if new text data is received
      Serial.printf("[%u] get Text: %s\n", num, payload);    
      webSocket.sendTXT(num, payload);    //Send back recived message to client

Upload sketch in NodeMCU, Open your Serial monitor and get IP or enter IP address l in a web browser

Beginning Guide  Websocket  NodeMCU
WebSocket Communication server page

Visit to get more tutorials on ESP8266

 760 total views,  1 views today