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.

Top Vue.js Developers in USA

Top Vue.js Developers in USA

Vue.js is an extensively popular JavaScript framework with which you can create powerful as well as interactive interfaces. Vue.js is the best framework when it comes to building a single web and mobile apps.

We, at HireFullStackDeveloperIndia, implement the right strategic approach to offer a wide variety through customized Vue.js development services to suit your requirements at most competitive prices.

Vue.js is an open-source JavaScript framework that is incredibly progressive and adoptive and majorly used to build a breathtaking user interface. Vue.js is efficient to create advanced web page applications.

Vue.js gets its strength from the flexible JavaScript library to build an enthralling user interface. As the core of Vue.js is concentrated which provides a variety of interactive components for the web and gives real-time implementation. It gives freedom to developers by giving fluidity and eases the integration process with existing projects and other libraries that enables to structure of a highly customizable application.

Vue.js is a scalable framework with a robust in-build stack that can extend itself to operate apps of any proportion. Moreover, vue.js is the best framework to seamlessly create astonishing single-page applications.

Our Vue.js developers have gained tremendous expertise by delivering services to clients worldwide over multiple industries in the area of front-end development. Our adept developers are experts in Vue development and can provide the best value-added user interfaces and web apps.

We assure our clients to have a prime user interface that reaches end-users and target the audience with the exceptional user experience across a variety of devices and platforms. Our expert team of developers serves your business to move ahead on the path of success, where your enterprise can have an advantage over others.

Here are some key benefits that you can avail when you decide to hire vue.js developers in USA from HireFullStackDeveloperIndia:

  • A team of Vue.js developers of your choice
  • 100% guaranteed client satisfaction
  • Integrity and Transparency
  • Free no-obligation quote
  • Portal development solutions
  • Interactive Dashboards over a wide array of devices
  • Vue.js music and video streaming apps
  • Flexible engagement model
  • A free project manager with your team
  • 24*7 communication with your preferred means

If you are looking to hire React Native developers in USA, then choosing HireFullStackDeveloperIndia would be the best as we offer some of the best talents when it comes to Vue.js.

Learn Node.js - Node.js API Development for Beginners

Learn Node.js API Development from absolute scratch. This video is for complete beginners getting started guide!

In this video you will learn the core fundamentals of Node JS so that you can start building API using Node JS. You will learn Modern JavaScript, Node JS event loop, Asynchronous programming, using node modules, npm modules and creating your own modules, creating server, connect to database and sending json responses.


Learn More

Node.js With Passport Authentication | Full Project

Full Stack Developers: Everything You Need to Know

MEAN Stack Tutorial MongoDB, ExpressJS, AngularJS and NodeJS

How to Perform Web-Scraping using Node.js

Moving from NodeJS to Go

Authenticate a Node ES6 API with JSON Web Tokens

The Complete Node.js Developer Course (3rd Edition)

Angular & NodeJS - The MEAN Stack Guide

NodeJS - The Complete Guide (incl. MVC, REST APIs, GraphQL)

Node.js: The Complete Guide to Build RESTful APIs (2018)