Jun 19, 2019· 5 mins to read

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


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?

  • screenshot

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

  • screenshot

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.

GET ws://websocket.example.com/ HTTP/1.1
Origin: http://example.com
Connection: Upgrade
Host: websocket.example.com
Upgrade: 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.

  • screenshot

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

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

project structure will look like

  • screenshot

add the following code in server.js

const express = require("express");

const app = express();

const http = require("http").Server(app);

const socketIO = require("socket.io")(http);
const PORT = process.env.PORT || 3000;

app.use(express.static(__dirname + "/public"));

socketIO.on("connection", () => {
  socketIO.emit("welcome", "web Socket Works");
});

http.listen(PORT, () => {
  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.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Socket.IO whiteboard</title>
  </head>
  <body>
    <h1 id="message"></h1>
  </body>
  <script src="socket.io/socket.io.js"></script>
  <script>
    const socket = io();

    socket.on("welcome", (data) => {
      console.log("data", data);
      document.getElementById("message").innerHTML = data;
    });
  </script>
</html>

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

npm run start

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

  • web socket demo

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

Copyright © Cloudnweb. All rights reserved.