Becoming a Nimble and Dexterous Developer using WebSockets in NodeJS

WebSockets: An Introduction:

WebSocket is a protocol that provides a way for the client and the server to communicate bidirectionally. The messages are exchanged between the server and the clients through communication channels. The messages can be exchanged as long as the communication channel is alive. They provide a way for instant messaging.

WebSockets Vs Http:

Http is a request/response protocol (i.e) a server cannot send any messages to the client unless the client makes a request for it. On the contrary, a WebSocket can send messages to the client even if the client did not request it. It provides a way for simultaneous communication between the client and the server.

Browser Support:

All modern browsers support WebSocket (Refer Link). This means that the necessary libraries for handling WebSockets are already available in the browser and so the web pages which use WebSockets can be loaded with ease.

Real-time application of WebSockets:

WebSockets are used in applications that require instant data. The following are some of the areas where WebSockets are used:

  • Chat application (text, audio, and video)
  • IoT devices
  • Stock related applications
  • Online auctions sites
  • Location tracking applications
  • Live interaction websites

Short Example :

Getting started:

  • Download and install nodejs from the link.
  • Create a directory for your sample application using the command line
    • mkdir chatApp
    • cd chatApp
  • Create package.json file
    • npm init
  • Install dependency packages
    • npm install express — save
    • npm install ws — save

Setting up the WebSocket server:

Create an app.js file:

Setting up the WebSocket client:

Create an index.html file:

Sending and Receiving messages:

Start the server with command node app.js

  • Open two different browsers and connect to node server running in localhost.

Start chatting!

Browser 1:

Browser 2:

Our simple chatbox with nodejs can now send and receive messages.

Leave a Reply

Your email address will not be published. Required fields are marked *

12 + nine =