Simple Websocket Example with Nodejs

Today’s topic is the WebSocket example with nodejs. WebSocket help to communicate the servers with clients in an async manner. The server and client can communicate and exchange data at the same time. WebSocket help to create real-time communication between web servers and clients.

The jQuery AJAX also can use to communicate with server, which is only one-way communication and only client can ask data from the server.

Whereas, Websocket provides two-way communication between server and client.The WebSocket connection is a persistent connection between a browser(client app) and the server. The server can send messages to the browser and the browser can respond back via the same connection.

Getting Started With Web Socket With Nodejs


The Web Socket API is cross platform standard for real-time communication between a client and the server.Web socket protocol has two type(ws:// and wss://) like http and https.

The client application must have the ability to connect the web socket and establish a connection. We will create two files –

  • server.js : This file will create a server that sends the response to the client app.
  • client.js : This file will use for the client app and listen to response from server.

Let’s install ws

We will install ws libs into nodejs application using the following command.

npm install ws

Create websocket server

We will create server.js file and add the below code into this file.

// server.js

const WebSocket = require('ws')

const wss = new WebSocket.Server({ port: 8080 })

wss.on('connection', ws => {
  ws.on('message', message => {
    console.log(`Received message => ${message}`)
  ws.send('Hello! Message From Server!!')

First, we will create ws connection object and open the connection on the 8080 port. Now, open the command line and run the server by the following command –

node server

Create Client Application For WebSocket

We will create client.js file and add the below code into this file –

// client.js

const WebSocket = require('ws')
const url = 'ws://localhost:8080'
const connection = new WebSocket(url)

connection.onopen = () => {
  connection.send('Message From Client') 

connection.onerror = (error) => {
  console.log(`WebSocket error: ${error}`)

connection.onmessage = (e) => {

Okay, Now we will start a client-side server by the following command.

node client

After the successfully connected client to server, the server start to send the message to client application.

6 thoughts to “Simple Websocket Example with Nodejs”

  1. when i try this server code it shows upgrade required message code not run ….. and also run client code means it shows [object object] error …how to overcome those error

Leave a Reply

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