Node JS WebSocket: Examples | Chat Features | Client-Server communication

Node JS WebSocket: Examples | Chat Features | Client-Server communication

Node JS WebSocket: Examples | Chat Features | Client-Server communication - Node Js WebSocket is a protocol and it makes two-way communication between the user and the server in real-time. Websockets are an ...

Node JS WebSocket: Examples | Chat Features | Client-Server communication - Node Js WebSocket is a protocol and it makes two-way communication between the user and the server in real-time. Websockets are an ...

What is WebSocket?

*Node Js *WebSocket is a protocol and it makes two-way communication between the user and the server in real-time. Websockets are an alternative for HTTP communication in web applications.

WebSockets offer bidirectional communication between client and server and Node Js WebSocket makes it possible to open an interactive communication between user’s browser and server to send messages to the server and it receives event-driven responses without having to poll the server for a reply.

Once the connection is established, then the channel is kept open, offering very fast connection with low latency and overhead.

Common use cases are chats, Online multiplayer games, Google Docs, etc.

To work with the Node Js WebSocket API for asynchronous communication between browser and servers, Here are some libraries in Node.js

  • WebSocket
  • Ws
  • Socket.io
  • Sockjs
  • Socketcluster
  • WebSocket as promised

Chat Features:

The beginning an user can select their name and the server will assign them some random color and will post some system message to the console that a new user was connected.

Then the user can post messages. When the user closes the browser window, the server will post another system message to the console that a user has disconnected. And also, every new user will receive the entire message history.

Here find HTML + CSS Code:

<!DOCTYPE html>

<html>

   <head>

       <meta charset=”utf-8″>

       <title>WebSockets – Simple chat</title>

       <style>

           * {

               font-family:tahoma;

               font-size:12px;

               padding:0px;

               margin:0px;

           }

           p { line-height:18px; }

           div { width:500px; margin-left:auto; margin-right:auto;}

           #content { padding:5px; background:#ddd; border-radius:5px;

               overflow-y: scroll; border:1px solid #CCC;

               margin-top:10px; height: 160px; }

           #input { border-radius:2px; border:1px solid #ccc;

               margin-top:10px; padding:5px; width:400px;

           }

           #status { width:88px;display:block;float:left;margin-top:15px; }

       </style>

   </head>

   <body>

       <div id=”content”></div>

       <div>

           <span id=”status”>Connecting…</span>

           <input type=”text” id=”input” disabled=”disabled” />

       </div>

       <script src=”//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js”></script>

       <script src=”frontend.js”></script>

 </body>

</html>

client → server, server → client communication:

For client →server communication I choose simple text because it is not necessary to wrap it in a more complicated structure.

When some user sends a message i.e client → server and then the server sends that message to all connected users i.e server →client.

But for the server –> client it’s a bit more complex. We have to separate steps into 3 different types of message:

  • The server assigns a color to the user
  • The server sends entire message history
  • The server broadcasts a message to all users

Therefore every message is a JavaScript Object encoded into JSON.

In this blog I am going to use the Node Js WebSocket library, so let us install with

$ npm install websocket Then your code:

var WebSocketServer = require(‘websocket’).server;
var WebSocketClient = require(‘websocket’).client;
var WebSocketFrame  = require(‘websocket’).frame;
var WebSocketRouter = require(‘websocket’).router;
var W3CWebSocket = require(‘websocket’).w3cwebsocket;

Node Js WebSocket example code:

const WebSocketServer = require(‘websocket’).server;

const http = require(‘http’);



const server = http.createServer(function(request, response) {

   // process HTTP request. Since we’re writing just WebSockets

   // server we don’t have to implement anything.

});

server.listen(4040, function() { });



// create the server

wsServer = new WebSocketServer({

   httpServer: server

});



// WebSocket server

wsServer.on(‘request’, function(request) {

   var connection = request.accept(null, request.origin);



   // This is the most important callback for us, we’ll handle

   // all messages from users here.

   connection.on(‘message’, function(message) {

       if (message.type === ‘utf8’) {

           // process WebSocket message

       }

   });



   connection.on(‘close’, function(connection) {

       // close user connection

   });

});

Client-side basically we need three callback:

$(function () {

           // if user is running mozilla then use it’s built-in WebSocket

           window.WebSocket = window.WebSocket || window.MozWebSocket;



           var connection = new WebSocket(‘ws://127.0.0.1:4040’);



           connection.onopen = function () {

           // connection is opened and ready to use

           };



           connection.onerror = function (error) {

           // an error occurred when sending/receiving data

           };



           connection.onmessage = function (message) {

           // try to decode json (I assume that each message

           // from server is json)

           try {

             var json = JSON.parse(message.data);

           } catch (e) {

             console.log(‘This doesn\’t look like a valid JSON: ‘,

                 message.data);

             return;

           }

           // handle incoming message

           };

       });

Client-side chat source code:

$(function () {

           “use strict”;

           // for better performance – to avoid searching in DOM

           var content = $(‘#content’);

           var input = $(‘#input’);

           var status = $(‘#status’);

           // my color assigned by the server

           var myColor = false;

           // my name sent to the server

           var myName = false;

           // if user is running mozilla then use it’s built-in WebSocket

           window.WebSocket = window.WebSocket || window.MozWebSocket;

           // if browser doesn’t support WebSocket, just show

           // some notification and exit

           if (!window.WebSocket) {

           content.html($(‘<p>’,

             { text: “Sorry, but your browser doesn’t support WebSocket.” }

           ));

           input.hide();

           $(‘span’).hide();

           return;

           }

           // open connection

           var connection = new WebSocket(‘ws://127.0.0.1:4040’);

           connection.onopen = function () {

           // first we want users to enter their names

           input.removeAttr(‘disabled’);

           status.text(‘Choose name:’);

           };

           connection.onerror = function (error) {

           // just in there were some problems with connection…

           content.html($(‘<p>’, {

               text: ‘Sorry, but there\’s some problem with your ‘ + ‘connection or the server is down.’

           }));

           };

           // most important part – incoming messages

           connection.onmessage = function (message) {

           // try to parse JSON message. Because we know that the server

           // always returns JSON this should work without any problem but

           // we should make sure that the massage is not chunked or

           // otherwise damaged.

           try {

             var json = JSON.parse(message.data);

           } catch (e) {

             console.log(‘Invalid JSON: ‘, message.data);

             return;

           }

           // NOTE: if you’re not sure about the JSON structure

           // check the server source code above

           // first response from the server with user’s color

           if (json.type === ‘color’) {

             myColor = json.data;

             status.text(myName + ‘: ‘).css(‘color’, myColor);

             input.removeAttr(‘disabled’).focus();

             // from now user can start sending messages

           } else if (json.type === ‘history’) { // entire message history

             // insert every single message to the chat window

             for (var i=0; i < json.data.length; i++) {

             addMessage(json.data[i].author, json.data[i].text,

                 json.data[i].color, new Date(json.data[i].time));

             }

           } else if (json.type === ‘message’) { // it’s a single message

             // let the user write another message

             input.removeAttr(‘disabled’);

             addMessage(json.data.author, json.data.text,

                        json.data.color, new Date(json.data.time));

           } else {

             console.log(“Hmm…, I have never seen JSON like this:”, json);

           }

           };

           /**

           * Send message when user presses Enter key

           */

           input.keydown(function(e) {

           if (e.keyCode === 13) {

             var msg = $(this).val();

             if (!msg) {

               return;

             }

             // send the message as an ordinary text

             connection.send(msg);

             $(this).val(”);

             // disable the input field to make the user wait until server

             // sends back response

             input.attr(‘disabled’, ‘disabled’);

             // we know that the first message sent from a user their name

             if (myName === false) {

               myName = msg;

             }

           }

           });

           /**

           * This method is optional. If the server wasn’t able to

           * respond to the in 3 seconds then show some error message

           * to notify the user that something is wrong.

           */

           setInterval(function() {

           if (connection.readyState !== 1) {

             status.text(‘Error’);

             input.attr(‘disabled’, ‘disabled’).val(

                 ‘Unable to communicate with the WebSocket server.’);

           }

           }, 3000);

           /**

           * Add message to the chat window

           */

           function addMessage(author, message, color, dt) {

           content.prepend(‘<p><span style=”color:’ + color + ‘”>’

               + author + ‘</span> @ ‘ + (dt.getHours() < 10 ? ‘0’

               + dt.getHours() : dt.getHours()) + ‘:’

               + (dt.getMinutes() < 10

                 ? ‘0’ + dt.getMinutes() : dt.getMinutes())

               + ‘: ‘ + message + ‘</p>’);

           }

       });

WebSocket server side code:

“use strict”;



process.title = ‘node-chat’;



const webSocketsServerPort = 4040;



const webSocketServer = require(‘websocket’).server;

const http = require(‘http’);



var history = [ ];



var clients = [ ];



function htmlEntities(str) {

   return String(str)

   .replace(/&/g, ‘&amp;’).replace(/</g, ‘<’)

   .replace(/>/g, ‘>’).replace(/”/g, ‘"’);

}



var colors = [‘purple’, ‘plum’, ‘orange’, ‘red’, ‘green’, ‘blue’, ‘magenta’ ];



colors.sort(function(a,b) {

   return Math.random() > 0.5;

});



var server = http.createServer(function(request, response) {



});



server.listen(webSocketsServerPort, function() {

   console.log(” Server listening port ”  + webSocketsServerPort);

});



var wsServer = new webSocketServer({

   httpServer: server

});



wsServer.on(‘request’, function(request) {

   console.log(‘ Connection origin ‘ + request.origin + ‘.’);

   var connection = request.accept(null, request.origin);



   var index = clients.push(connection) – 1;

   var userName = false;

   var userColor = false;

   console.log(‘ Connection is accepted.’);



   if (history.length > 0) {

       connection.sendUTF(JSON.stringify({ type: ‘history’, data: history} ));

   }



  connection.on(‘message’, function(message) {

   if (message.type === ‘utf8’) {



       if (userName === false) {



           userName = htmlEntities(message.utf8Data);



           userColor = colors.shift();

           connection.sendUTF(

               JSON.stringify({ type:’color’, data: userColor }));

           console.log(‘ User is known as: ‘ + userName + ‘ with ‘ + userColor + ‘ color.’);

         } else {

           console.log(‘ Received Message from ‘ + userName + ‘: ‘ + message.utf8Data);



           var obj = {

             time: (new Date()).getTime(),

             text: htmlEntities(message.utf8Data),

             author: userName,

             color: userColor

         };

         history.push(obj);

         history = history.slice(-100);



           var json = JSON.stringify({ type:’message’, data: obj });

           for (var i=0; i < clients.length; i++) {

             clients[i].sendUTF(json);

         }

     }

   }

   });



   connection.on(‘close’, function(connection) {

   if (userName !== false && userColor !== false) {

       console.log(connection.remoteAddress + ” was disconnected.”);



       clients.splice(index, 1);



       colors.push(userColor);

   }

   });

});

Now run the server script. Now you can open your HTML, if everything works fine it should ask your name to print in the console.

node-js web-development

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Hire Node.JS Developers | Skenix Infotech

We are providing robust Node.JS Development Services with expert Node.js Developers. Get affordable Node.JS Web Development services from Skenix Infotech.

How to Hire Node.js Developers And How Much Does It Cost?

A Guide to Hire Node.js Developers who can help you create fast and efficient web applications. Also, know how much does it cost to hire Node.js Developers.

Top Node.js Development Companies and Expert NodeJS Developers

A thoroughly researched list of top NodeJS development companies with ratings & reviews to help hire the best Node.JS developers who provide development services and solutions across the world. List of Leading Node.js development Service Providers...

Hire Web Developer

Looking for an attractive & user-friendly web developer? HourlyDeveloper.io, a leading web, and mobile app development company, offers web developers for hire through flexible engagement models. You can **[Hire Web...

Hire Node JS Developer from Expert Node JS Development Company

NodeJS Development Company-Hire Node JS developer from the most prominent NodeJS development company, Mobiweb and get remarkable Node.js app development services.