What are Web Sockets ? Implementing Web Sockets in Node.js
Tags: showdev, node, tutorial, webdev
Published: 2019-06-19 17:25:49

---
title: What are Web Sockets ? Implementing Web Sockets in Node.js
published: true
description: What are Web Sockets ? Implementing Web Sockets in Node.js
tags: showdev,node.js,tutorial,webdev
canonical_url: https://cloudnweb.dev/2019/06/what-are-web-sockets-implementing-web-sockets-in-node-js/
---
<!-- wp:paragraph -->
<p>In this article, we will see What are Web Sockets and Implementing WebSockets in Node.js</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>What are Web Sockets?</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>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. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>you can ask me why we need a separate protocol when we can send and receive the messages through HTTP.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>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</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>How HTTP Protocol works?</h3>
<!-- /wp:heading -->

<!-- wp:gallery {"ids":[653]} -->
<ul class="wp-block-gallery columns-1 is-cropped"><li class="blocks-gallery-item"><figure><img src="https://cloudnweb.dev/wp-content/uploads/2019/06/http-1024x654.jpeg" alt="" data-id="653" data-link="https://cloudnweb.dev/?attachment_id=653#main" class="wp-image-653"/></figure></li></ul>
<!-- /wp:gallery -->

<!-- wp:paragraph -->
<p>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.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>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. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>we could solve this problem though with <strong>Http Long polling</strong></p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>What is Http Long Polling ? </h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Http Long Polling is something  where the client polls the server requesting new information.&nbsp; 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 </p>
<!-- /wp:paragraph -->

<!-- wp:gallery {"ids":[659]} -->
<ul class="wp-block-gallery columns-1 is-cropped"><li class="blocks-gallery-item"><figure><img src="https://cloudnweb.dev/wp-content/uploads/2019/06/http-longpolling.png" alt="" data-id="659" data-link="https://cloudnweb.dev/?attachment_id=659#main" class="wp-image-659"/></figure></li></ul>
<!-- /wp:gallery -->

<!-- wp:paragraph -->
<p>problem with long polling is that it takes lots of resources to process the request.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>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.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>To solve all this problems, WebSockets comes into play.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>How WebSocket Works?</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>web socket is bi-directional communication. client sends the request with <strong>upgrade </strong>keyword and other metadata. </p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>GET ws://websocket.example.com/ HTTP/1.1
Origin: http://example.com
Connection: Upgrade
Host: websocket.example.com
Upgrade: websocket</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>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.</p>
<!-- /wp:paragraph -->

<!-- wp:gallery {"ids":[663]} -->
<ul class="wp-block-gallery columns-1 is-cropped"><li class="blocks-gallery-item"><figure><img src="https://cloudnweb.dev/wp-content/uploads/2019/06/websockets.png" alt="" data-id="663" data-link="https://cloudnweb.dev/?attachment_id=663#main" class="wp-image-663"/></figure></li></ul>
<!-- /wp:gallery -->

<!-- wp:paragraph -->
<p>web sockets are low latency communication protocol which takes less computational resources when compared with Http Long Polling.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Implementing WebSockets in Node.js</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>we will see how we can implement websockets in node.js. we will be using a library called <strong>socket.io</strong> for web sockets in node.js.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>run the following commands to bootstrap the application</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>npm init --yes
npm install --save socket.io express 
npm install --save-dev nodemon</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>project structure will look like</p>
<!-- /wp:paragraph -->

<!-- wp:gallery {"ids":[670]} -->
<ul class="wp-block-gallery columns-1 is-cropped"><li class="blocks-gallery-item"><figure><img src="https://cloudnweb.dev/wp-content/uploads/2019/06/projectstructure-1.png" alt="" data-id="670" data-link="https://cloudnweb.dev/?attachment_id=670#main" class="wp-image-670"/></figure></li></ul>
<!-- /wp:gallery -->

<!-- wp:paragraph -->
<p>add the following code in server.js</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>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}`);
})</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Firstly, you import the express and start the server.you need to pass the http server to socket.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><strong>.on('connection')</strong> start establish the socket connection with client</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>To emit the event, you need to use <strong>.emit()</strong> with the event name. Here, you pass the event <strong>welcome</strong> with the data <strong>web Socket Works</strong></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p> Further , To receive the event you need to use <strong>.on('event name')</strong> </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>create a file <strong>index.html</strong> inside the public directory and add the following code.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>&lt;!doctype html>
&lt;html>
    &lt;head>
            &lt;meta charset="UTF-8">
            &lt;title>Socket.IO whiteboard&lt;/title>
    &lt;/head>
    &lt;body>
        &lt;h1 id="message">&lt;/h1>
    &lt;/body>
    &lt;script src="socket.io/socket.io.js">&lt;/script>
    &lt;script>
        const socket = io();

        socket.on('welcome',data => {
            console.log("data",data);
             document.getElementById('message').innerHTML = data;
        })
    &lt;/script>
&lt;/html></code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Now, you need to run the server with the following command.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>npm run start</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>if you visit the url <strong>http://localhost:3000</strong> . you will see something like this</p>
<!-- /wp:paragraph -->

<!-- wp:gallery {"ids":[672]} -->
<ul class="wp-block-gallery columns-1 is-cropped"><li class="blocks-gallery-item"><figure><img src="https://cloudnweb.dev/wp-content/uploads/2019/06/web-socket-demo-1024x493.png" alt="" data-id="672" data-link="https://cloudnweb.dev/?attachment_id=672#main" class="wp-image-672"/></figure></li></ul>
<!-- /wp:gallery -->

<!-- wp:paragraph -->
<p>Therefore, several clients can connect with the sockets and communicate with server/clients.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Cool Tech. Right?.. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p> In conclusion , We can use Web Sockets in different kind of applications</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li> Real-time applications </li><li> Chat apps </li><li> IoT (internet of things) </li><li> Online multiplayer games </li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>Complete Source Code : <a href="https://codesandbox.io/s/socket-demo-y0bve">https://codesandbox.io/s/socket-demo-y0bve</a></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>we have seen  What are Web Sockets and Implementing WebSockets in Node.js  in this article.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>  we will see in depth of web sockets in upcoming article. until then, <strong>Happy Hacking</strong> :-)</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p> Meanwhile , To Know more about web development</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li><a href="https://cloudnweb.dev/2019/05/nginx-for-front-end-developers/">Nginx for Front-end Developers</a></li><li><a href="https://cloudnweb.dev/2019/06/immutablejs-for-react-developers/">ImmutableJs for React Developers</a></li></ul>
<!-- /wp:list -->