How to use WebSockets in JavaScript

WebSocket protocol is used for persistent communication of data between the server and client. We can transfer data in both directions in the form of a "packet" using HTTP and HTTPS protocols.

Installing ws using npm

To use WebSockets in JavaScript, we have to install the ws package by using npm.

$ npm i ws

Import/require WebSocket

Before using WebSockets in JavaScript, we must import it into our file or project. To do this, we can use both import and require depending upon our application.

Using 'import'

import Websocket from 'ws'

Using 'require'

const WebSocket = require(ws);

Simple server-client example

In this example, we are simply making a messaging app. When we run the code below, we will see a simple messaging app.

const WebSocket = require(`ws`);
const wss = new WebSocket(`ws://localhost:3000`);

wss.onmessage = function (e) {
  console.log("I'm client")
  let message = JSON.parse(e.data);
  console.log(message);
};
Simple messaging app

Explanation of server.js

  • Line 1: We import the ws package.
  • Line 2: We assign the communication port on 3000.
  • Line 4: We make a function using ws.on.
  • Line 5: We specify the message ("I'm server"), which will be displayed.
  • Line 6: We create a message "Connection Established!. M2C!"
  • Line 7: We send the message to the client.

Explanation of client.js

  • Line 1: We import the ws package.
  • Line 2: We assign the communication port on 3000.
  • Line 4: We make a function using ws.onmessage that will receive the message.
  • Line 5: We display "I'm client" on the console.
  • Line 6: We receive the message in the message variable.
  • Line 7: We display the received message on the console.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved