How to use Websocket in NodeJs

Websocket is generally used for real-time and bidirectional communications with server side like NodeJs and client side. It enables the client to get real-time data without continuous polling.

WebSocket in Nodejs
WebSocket in Nodejs

What is Websocket?

Websocket is computer communication protocol, providing simultaneous two-way communication channels over a single transmission controll protocol connection.

Installing websocket in nodejs

First install the ‘ws‘ module by running the following command. You should add the ‘express’ module for creating the nodejs server.

Creating Websocket server

Creating the server.js file with express and http. Below is explanation about the websocket.

Server side explanation:

  • We import the ‘ws’ module and create the websocket server.
  • We listen for ‘connection’ event which occur when client connect to the server.
  • Inside the ‘connection’ event listener, we handled the incoming message from the clients using the ‘message’ event and we are sending the messages back to the client using ‘ws.send()’
  • We also listen for ‘close’ event when client disconnect to the server.

Client Side Explanation:

  • We create a WebSocket instance by passing the server’s URL (ws://localhost:8080) to the WebSocket constructor.
  • We listen for 'open' and 'message' events to handle the connection and incoming messages from the server, respectively.
  • We define a function (sendMessage()) to send messages to the server when the user clicks the “Send” button.

Thank you for connecting with us. Please see other useful NodeJs tutorials, which are below:

How to use AWS SDK in NodeJs? See all operations

Node.js SSL Setup on Aws EC2 in Easy Short Way

How to use Map in JavaScript? See all operations.

JavaScript String Methods With All Complete Examples

Don’t miss new tips!

We don’t spam! Read our [link]privacy policy[/link] for more info.

Leave a Comment

Translate »
Scroll to Top