Saturday 3 December 2016

Push messages to browser/clients with NodeJS WebSocket

Hi Folks, off late I have been trying to do a POC on pushing messages from server to all the connected clients and found that websocket can be used for it in conjunction with NodeJS. So I am putting it all over to this post.

Following are the prerequisites in order to run the setup:
  1. NodeJS Installation (We need npm to install packages) Download Link
  2. NPM Packages (websocket, http-server, finalhandler, serve-static).
NPM package installation commands:
  • npm install websocket
  • npm install http-server
  • npm install finalhandler
  • npm install serve-static
After successful installation of NodeJS and above mentioned npm packages we can start off writing the code. We need following three files hosted on a folder (All the npm package installation commands will be executed on this folder).
  1. frontend.html.
  2. frontend.js (NodeJS Frontend).
  3. backend.js (NodeJS Backend).
Following is the source code of above files:

frontend.html

frontend.js

backend.js


Following is the directory structure of project: