How To Create WebSocket Server And Client in NodeJS

How To Create WebSocket Server And Client in NodeJS. In this blog, we introduce WebSocket, why is it good to use and after that we invite you to read our step by step tutorial about how to create a WebSocket server and client in Node.js.

Would you like to build interactive, event driven applications like chat applications, online gaming, or live dashboards? If the answer is yes, then why don’t you consider using WebSocket server? The ws library is a popular choice for WebSocket server development in Node.js. This library allows you to quickly implement WebSocket functionality on the server side. Create WebSocket servers that listen for incoming connections, manage client connections, and broadcast messages in real time.

What is more, establishing WebSocket connections using JavaScript is an effective way to build interactive, event driven applications like chat applications, online gaming, or live dashboards. WebSocket servers, such as the popular ws library for WebSocket server development in Node.js, make it easy to implement WebSocket functionality on the server side. With WebSocket servers and clients, you can create dynamic, responsive web applications that push updates and data instantly, providing an engaging and interactive user experience. This guide shows you how to create both WebSocket servers and clients in Node.js, opening up a whole new world of possibilities for real time web development.

What is WebSocket?

Websocket is a great, fast and simple to use tool for WebSocket client and server implementation. It makes it easy to establish a connection between a web browser and a server. Create real time web applications that push updates and data instantly, providing an engaging and interactive user experience. If you want to learn more about WebSockets, we have a dedicated guide that covers everything from usage to testing WebSocket servers. It includes information about what a WebSocket client and server are, a list of WebSocket API providers, and much more.

Moreover, WebSocket is a highly effective communication protocol that allows for real time and bidirectional exchange of data between a server and clients. In the realm of Node.js, the creation of WebSocket clients and servers is a simple process, made possible through libraries like ws and This guide will take you through the necessary steps for setting up a WebSocket server and client in Node.js.

One significant difference between WebSocket and HTTP servers is that WebSocket servers do not have any default routes. Routes are not necessary in this protocol, and you can simply use a string to send and receive data from the client side. A good practice is to send a JSON object serialized to a string.

Why Use WebSocket?

Simple because Websocket is a great protocol for providing real time updates to users. Compatible tool with various platforms like Android, iOS, Mac, Windows, and more. One of the benefits of Websocket is the ability to send multiple requests simultaneously and have multiple connections. You can also enable proxies for added security. There are many open source platforms available to help you build WebSocket apps.

Here are some reasons why you might choose to use WebSocket:

  • Real time Communication – WebSocket enables real time bidirectional communication between clients and servers. This is particularly useful for applications that require instant data updates, such as chat applications, online gaming, financial trading platforms, and collaborative editing tools.
  • Reduced Latency – Unlike traditional HTTP polling or long polling, which involve repeatedly sending requests to the server, WebSocket maintains a persistent connection. This results in lower latency and reduced overhead compared to techniques that involve repeatedly opening and closing connections.
  • Efficient Use of Resources – WebSocket reduces the overhead associated with opening and closing connections for every request. The persistent connection is more efficient in terms of both server and network resources, making it suitable for applications with a large number of simultaneous connections.
  • Bi Directional Communication – WebSocket allows data to be sent in both directions from the client to the server and from the server to the client over the same connection. This is particularly beneficial for applications that require real time updates from either end.
  • Push Notifications – WebSocket is commonly used for implementing push notification systems. Servers can push data to connected clients as soon as new information becomes available, eliminating the need for clients to poll the server continuously for updates.
  • Event Driven Architecture – WebSocket fits well with event driven architectures. It allows the server to send events to clients as they occur, enabling a more responsive and interactive user experience.
  • WebSockets over Web – WebSocket is designed to work seamlessly over the web, making it a suitable choice for web applications. It operates over the same ports (80 and 443) as HTTP and HTTPS, simplifying firewall and proxy configuration.
  • Cross Domain Communication – WebSocket supports cross domain communication, allowing clients to connect to servers on different domains. This is particularly useful for building distributed systems or services that span multiple domains.
  • Support for Various Protocols – WebSocket is not limited to a specific application domain. It can be used with various application-level protocols, making it versatile and adaptable to different use cases.

How To Create WebSocket Server And Client in NodeJS

In this section, we will explore the process to create a WebSocket server and client in Node.js.

Build a WebSocket Server using Node.js

To start building your WebSocket app, make sure you have Nodejs and NPM installed on your system. If you don’t have it, you can download and install it from Once you have NodeJs installed, open a terminal and enter the following commands (for Linux or Mac users):

For Windows type below command to create a new directory to build your WebSocket Server with NodeJS. 

					mkdir nodejs-websocket-server
cd nodejs-websocket-server

After that, run a command to install the ws library as a dependency.

					npm install ws

With this, you create a package.json file in your project and install the dependency in the node_modules directory. After installation, you can create javascript file name as main.js

					// Creating a new websocket server
const wss = new WebSocketServer.Server({ port: 8080 })
// Creating connection using websocket
wss.on("connection", ws => {
    console.log("new client connected");
    // sending message to client
    ws.send('Welcome, you are connected!');
    //on message from client
    ws.on("message", data => {
        console.log(`Client has sent us: ${data}`)
    // handling what to do when clients disconnects from server
    ws.on("close", () => {
        console.log("the client has connected");
    // handling client connection error
    ws.onerror = function () {
        console.log("Some Error occurred")
console.log("The WebSocket server is running on port 8080");

This code creates a basic WebSocket Server for you. The code is self explanatory and can be edited as per your needs. You can provide any port you want while creating the WebSocket server. To test it, open up a terminal and type:

					node main.js

Below is the output after typing the command you will get the desired output.

Building A WebSocket Client For NodeJS WebSocket Server

To ensure the NodeJS program (WebSocket server) stays active, leave it running in the terminal. Now it’s time to test the WebSocket server. To accomplish this, we require a WebSocket client.

A convenient method to test any WebSocket server is to utilize the Online WebSocket tester by PieSocket. All you need to do is open the given link and then enter ws://localhost:8080 to test the WebSocket server you previously created.

Alternatively, we can quickly create a WebSocket client in HTML and JavaScript. To do so, start by creating an HTML file (WebSocket client) and include the following Javascript code snippet in the file to connect to the server we launched on our local machine.

					<!DOCTYPE html>
	<title>NodeJS WebSocket Server</title>
	<h1>Hello world</h1>
const ws = new WebSocket("ws://localhost:8080");
ws.addEventListener("open", () =>{
  console.log("We are connected");
  ws.send("How are you?");
ws.addEventListener('message', function (event) {
<script>class RocketElementorAnimation{constructor(){this.deviceMode=document.createElement("span"),"elementor-device-mode-wpr",this.deviceMode.setAttribute("class","elementor-screen-only"),document.body.appendChild(this.deviceMode)}_detectAnimations(){let t=getComputedStyle(this.deviceMode,":after").content.replace(/"/g,"");this.animationSettingKeys=this._listAnimationSettingsKeys(t),document.querySelectorAll(".elementor-invisible[data-settings]").forEach(t=>{const e=t.getBoundingClientRect();if(e.bottom>=0&&<=window.innerHeight)try{this._animateElement(t)}catch(t){}})}_animateElement(t){const e=JSON.parse(t.dataset.settings),i=e._animation_delay||e.animation_delay||0,n=e[this.animationSettingKeys.find(t=>e[t])];if("none"===n)return void t.classList.remove("elementor-invisible");t.classList.remove(n),this.currentAnimation&&t.classList.remove(this.currentAnimation),this.currentAnimation=n;let s=setTimeout(()=>{t.classList.remove("elementor-invisible"),t.classList.add("animated",n),this._removeAnimationSettings(t,e)},i);window.addEventListener("rocket-startLoading",function(){clearTimeout(s)})}_listAnimationSettingsKeys(t="mobile"){const e=[""];switch(t){case"mobile":e.unshift("_mobile");case"tablet":e.unshift("_tablet");case"desktop":e.unshift("_desktop")}const i=[];return["animation","_animation"].forEach(t=>{e.forEach(e=>{i.push(t+e)})}),i}_removeAnimationSettings(t,e){this._listAnimationSettingsKeys().forEach(t=>delete e[t]),t.dataset.settings=JSON.stringify(e)}static run(){const t=new RocketElementorAnimation;requestAnimationFrame(t._detectAnimations.bind(t))}}document.addEventListener("DOMContentLoaded",;</script></body>

To establish a WebSocket connection, simply open the HTML file in your browser. You’ll receive confirmation of the connection in the terminal. To view the connection details, go to your browser’s developer tools, click on the Networks tab, and inspect the element. Additionally, you can view messages from the WebSocket server by checking the console logs in the developer tools.

Thank you for reading How To Create WebSocket Server And Client in NodeJS. That is it. Now conclusion part below. 

How To Create WebSocket Server And Client in NodeJS: Conclusion

Developing WebSocket applications with Node.js can revolutionize your web development, allowing for real-time data transmission between servers and clients. By using the WS library on the server side and JavaScript on the client side, you can create engaging experiences that respond rapidly to user actions. With WebSocket technology, you can eliminate the need for constant polling and provide near-instant updates, making your applications more efficient and user-friendly. So, don’t hesitate to explore the endless possibilities of WebSocket technology in your Node.js projects.

Avatar for Hitesh Jethva
Hitesh Jethva

I am a fan of open source technology and have more than 10 years of experience working with Linux and Open Source technologies. I am one of the Linux technical writers for Cloud Infrastructure Services.

0 0 votes
Article Rating
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x