What are Web Sockets ? Implementing Web Sockets in Node.js

In this article, we will see What are Web Sockets and Implementing WebSockets in Node.js

What are Web Sockets?

Web Sockets are nothing but a communication protocol which allows real time interactive communication between client which is a browser and server. It uses a completely different protocol that allows bidirectional data flow, making it unique against HTTP.

you can ask me why we need a separate protocol when we can send and receive the messages through HTTP.

There are some scenario where we need to get the data in a real time. For Example, building a chat application or any other application which need a real time notification. we could not use HTTP protocol. i will explain the reason why in this article

How HTTP Protocol works?

In Http protocol, every time we need to get the updated data or notification, we need to request the server. server will respond with the updated data.

problem with this approach is , it makes lots of network calls which cause latency in the application.every time we need to request the server and update the data.

we could solve this problem though with Http Long polling

What is Http Long Polling ?

Http Long Polling is something where the client polls the server requesting new information.  The server holds the request open until new data is available. Once available, the server responds and sends the new information. When the client receives the new information, it immediately sends another request, and the operation is repeated

problem with long polling is that it takes lots of resources to process the request.

consider if there are million users accessing the application. it takes lots of computational resources just to maintain the communication between the client and server.

To solve all this problems, WebSockets comes into play.

How WebSocket Works?

web socket is bi-directional communication. client sends the request with upgrade keyword and other metadata.

1GET ws://websocket.example.com/ HTTP/1.1
2Origin: http://example.com
3Connection: Upgrade
4Host: websocket.example.com
5Upgrade: websocket

Server receives the request. if server supports the websockets, it will send a handshake response. once it sends the reponse, bi - directional communication establishes between client and server.

web sockets are low latency communication protocol which takes less computational resources when compared with Http Long Polling.

Implementing WebSockets in Node.js

we will see how we can implement websockets in node.js. we will be using a library called socket.io for web sockets in node.js.

run the following commands to bootstrap the application

1npm init --yes
2npm install --save socket.io express
3npm install --save-dev nodemon

project structure will look like

add the following code in server.js

1const express = require("express")
3const app = express()
5const http = require("http").Server(app)
7const socketIO = require("socket.io")(http)
8const PORT = process.env.PORT || 3000
10app.use(express.static(__dirname + "/public"))
12socketIO.on("connection", () => {
13 socketIO.emit("welcome", "web Socket Works")
16http.listen(PORT, () => {
17 console.log(`app is listening to port ${PORT}`)

Firstly, you import the express and start the server.you need to pass the http server to socket.

.on('connection') start establish the socket connection with client

To emit the event, you need to use .emit() with the event name. Here, you pass the event welcome with the data web Socket Works

Further , To receive the event you need to use .on('event name')

create a file index.html inside the public directory and add the following code.

1<!DOCTYPE html>
3 <head>
4 <meta charset="UTF-8" />
5 <title>Socket.IO whiteboard</title>
6 </head>
7 <body>
8 <h1 id="message"></h1>
9 </body>
10 <script src="socket.io/socket.io.js"></script>
11 <script>
12 const socket = io()
14 socket.on("welcome", data => {
15 console.log("data", data)
16 document.getElementById("message").innerHTML = data
17 })
18 </script>

Now, you need to run the server with the following command.

1npm run start

if you visit the url http://localhost:3000 . you will see something like this

Therefore, several clients can connect with the sockets and communicate with server/clients.

Cool Tech. Right?..

In conclusion , We can use Web Sockets in different kind of applications

  • Real-time applications
  • Chat apps
  • IoT (internet of things)
  • Online multiplayer games

Complete Source Code : https://codesandbox.io/s/socket-demo-y0bve

we have seen What are Web Sockets and Implementing WebSockets in Node.js in this article.

we will see in depth of web sockets in upcoming article. until then, Happy Hacking :-)

Meanwhile , To Know more about web development

To Read More

Modern React Redux Toolkit - Login ...

User Authentication is one of the common workflow in web applications. In this t...

Building Nodejs Microservice - A Cl...

This Article explains everything about how to build Nodejs Microservices in clou...

I Accidentally wiped the entire dat...

One of the tragic accident in my job turned out to be good learning for me in re...