What is WebSocket?

Posted on

by

in

Using WebSocket in the Internet of Things (IOT) projects

Introduction

Have you heard about WebSocket and how to take advantage of its features in your Internet of Things (IOT) projects? In this post, I will try to answer some of the common questions about this useful protocol which is being used for real-time streaming of data between the clients and the WebServer.

What is WebSocket?

WebSocket is a client-server communication protocol running on top of your TCP (Transmission Control Protocol). It supports bi-directional full duplex message exchanges between a client (usually a web browser) and a web server with little overhead compared to HTTP. This makes it an ideal protocol for applications that requires “real-time” message exchange and asynchronous updates.

That is quite a handful of definitions. But let us try to break it down by explaining first by explaining how HTTP (Hypertext Transfer Protocol) works and comparing it to WebSocket.

HTTP Communication

HTTP Communication Protocol
  • Client (usually browsers) request resources like pages, images, or files, and then the WebServer returns a response then communication is terminated. The opening and closing of connections add overhead for each request-response cycle.
  • If the server contains new data then it does not push it to the client unless it requests it.

WebSocket Communication

WebSocket IOT - Protocol
  • The protocol automatically upgrades to WebSocket when the Initial HTTP Handshake (Upgrade) is successful. Please see the next section on how this upgrade works.
  • The client can send messages to WebServer. The WebServer can push messages to the Client. Both can send and receive messages at the same time. In effect, this protocol is full-duplex and bi-directional.
  • Connection is persistent so it does not get created/destroyed for each request/response cycle. This makes it ideal for “Real-Time” applications as there is less overhead. If one of the participants disconnects then it closes the connection and does not get reconnected.

How is a WebSocket connection established?

The process of establishing a WebSocket connection is done thru the protocol handshake using a pair of WebSocket Handshake Request and a WebSocket Handshake Response.

Below is an example of a WebSocket Handshake Request

GET ws://192.168.100.195/ws HTTP/1.1
Host: 192.168.100.195
Connection: Upgrade
Pragma: no-cache
Cache-Control: no-cache
User-Agent: Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Mobile Safari/537.36
Upgrade: websocket
Origin: http://192.168.100.195
Sec-WebSocket-Version: 13
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9
Sec-WebSocket-Key: tnl0nQWIsWwEMpj9V+dV3A==
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits

The sample WebSocket Handshake Response.

HTTP/1.1 101 Switching Protocols
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Accept: n62Htl716IZqfTO319eJ6Ig1PMI=
Accept-Ranges: none

You would see this WebSocket Protocol Handshake request/response when you open your developer tool and go to the network tab of your browsers. You would see that the status will become 101 Switching Protocols when the HTTP connection is upgraded to a WebSocket connection.

Notice the scheme in the “GET ws://192.168.100.195/ws HTTP/1.1” header which uses the ws(WebSocket) or wss(WebSocket Secure). This is similar to how HTTP and HTTPS are structured with wss as the most secure between the two.

Once the initial handshake is completed and the connection is upgraded to a WebSocket connection then the message exchange between the client and the server can start. This connection remains and is persistent until one of them disconnects.

Sending WebSocket messages

Sending messages to the WebSocket server is as easy as calling socket.send("message") in your Javascript code. The code below is how you can handle the connections with your WebSocket server.

// Creates socket connection to our server
const socket = new WebSocket('ws://localhost:5000/ws');

// Callback function when connection is open
socket.onopen = function () {
  socket.send("donsky");
};

// Callback function when connection is received from websocket server
socket.onmessage = function(event) {
  console.log(event.data);
};

// Callback function when connection is closed
socket.onclose = function(event) {
  console.log("Connection is closing...");
};

// Callback function when connection encounters an error
socket.onerror = function(event) {
  onSocketError(event);
};

Why WebSocket is good for IOT projects?

WebSocket is an excellent mode of communication for displaying real-time data that you want to send from your Server to your clients. Example applications include Chat apps, Stock prices, and Gaming programs that display information to your user and need to be updated asynchronously in real-time.

WebSocket is very much applicable to IOT-based projects since we are dealing with sensors or actuators that we need to respond to immediately. Since most project nowadays requires control from Web Browsers then this is an ideal protocol to use. Most browsers support the WebSocket protocol.

I have used this communication protocol in many projects that I have done like:

A typical example is when you are controlling your WIFI robot car using your mobile phone. The web application you are using to control your robot car should respond immediately otherwise your robot car may crash.

Take a look at the video below of my ESP32 WIFI robot car that uses WebSocket to control its movement. Once I clicked the control to turn left then my car should automatically turn left and turn right if I clicked the right control. If I had used HTTP here, then my car might not be as responsive as it can be because of the overhead that I have discussed above.

WebSocket versus other IOT protocol

MQTT versus REST

MQTT (MQ transport Telemetry) is based on the publish-subscribe model and is aimed at devices with limited network bandwidth. This protocol was established with the goal of machine-to-machine communication in mind.

WebSocketMQTT
Bi-directional and full duplexuses the publish/subscribe model
does not have topic and priority conceptsit has the concept of topic and priority
incurs latency when there are multiple devices connectedminimal overhead when using multiple IOT devices
Sending and receiving of messages is from server to clientsmultiple publishers and subscribers can participate in the communication

Both these two protocols serve different purposes and are usually complementary technologies to each other.

REST versus WebSocket

REST (Representational State Transfer) is an architectural style commonly used when serving web service API.

WebSocketREST
Stateful protocolStateless
Bi-directional and is a full duplexUni-directional and based on the request-response model.
Uses IP and Port assignment to communicate between client and serverUses HTTP Methods (GET, POST, PUT, DELETE) and has the concept of resources
Faster as connections are persistent so one TCP Connection is used.Slower as every request/response cycle uses a new TCP connection with additional headers per request

The REST is used for serving an API web service request to clients and serves a different purpose than WebSocket. They are both useful in the use cases that they are trying to solve and WebSocket does not replace the HTTP REST interface.

Wrap up

We have discussed the basics of WebSocket in this post and explained why it is an ideal communication protocol in our Internet of Things (IOT) projects.

Happy Exploring!

If you like my post then please consider sharing this. Thanks!

16 responses to “Using WebSocket in the Internet of Things (IOT) projects”

  1. Plot Real-time Chart display of Sensor Readings – ESP8266/ESP32

    […] that require real-time updates. If you want to know more about WebSocket then please look at my Using WebSocket in the Internet of Things (IOT) projects. I have used this protocol in different projects […]

  2. ESP32 Robot Car Using Websockets – donskytech.com

    […] is beyond the scope of this post. If you want to know more about WebSocket then please look at my Using WebSocket in the Internet of Things (IOT) projects […]

  3. Raspberry Pi Object Counting using Infrared sensor –

    […] you want to know more about WebSocket then please look at my Using WebSocket in the Internet of Things (IOT) projects […]

  4. Building a MicroPython Wifi Robot Car – donskytech.com

    […] Related Content: Using WebSocket in the Internet of Things (IoT) projects […]

  5. How to enable Websockets in Mosquitto? – donskytech.com

    […] Read More: Using WebSocket in the Internet of Things (IoT) projects […]

  6. Publish and Subscribe MQTT messages over WebSocket

    […] Read More: Using WebSocket in the Internet of Things (IoT) projects […]

  7. Arduino MQTT Example Project – BMP/BME 280 Weather Station

    […] Content: Using WebSocket in the Internet of Things (IoT) projectsPublish and Subscribe MQTT messages over […]

  8. Pico W -MicroPython MQTT – BMP/BME 280 Weather Station

    […] Content: Using WebSocket in the Internet of Things (IoT) projectsPublish and Subscribe MQTT messages over […]

  9. Using WebSocket in MicroPython – A Practical Example

    […] Related Content: Using WebSocket in the Internet of Things (IoT) projects […]

  10. Node-Red – Display Arduino Sensor Readings thru WebSocket

    […] Related Content: Using WebSocket in the Internet of Things (IoT) projects […]

  11. Arduino Fingerprint Door Lock using ESP32 with a Web App

    […] Related Content: Using WebSocket in the Internet of Things (IoT) projects […]

  12. Raspberry Pi Pico W – Web Server to control components

    […] Content: Using WebSocket in the Internet of Things (IoT) projectsUsing WebSocket in MicroPython – A Practical […]

  13. Display Real-Time Updates Using Python, Flask, and Websocket

    […] Read More: Using WebSocket in the Internet of Things (IoT) projects […]

  14. Building a Raspberry Pi Pico W WiFi Robot Car – donskytech.com

    […] Related Content: Using WebSocket in the Internet of Things (IoT) projects […]

  15. OpenCV QR Code Detection using your web browser – donskytech.com

    […] Content: Using WebSocket in the Internet of Things (IoT) projectsDisplay Real-Time Updates Using Python, Flask, and […]

  16. Arduino Stepper Motor Control Project thru WiFi – donskytech.com

    […] Related Content: Using WebSocket in the Internet of Things (IoT) projects […]

Leave a Reply

Your email address will not be published. Required fields are marked *