How to Create a WebSocket Connection in JavaScript ?
Last Updated :
21 Mar, 2024
WebSocket is a powerful communication protocol enabling real-time data exchange between clients and servers. In this guide, we'll explore how to establish a WebSocket connection using JavaScript. Below are the steps outlined for implementation:
Approach
"To establish a WebSocket connection in JavaScript, we need to configure a WebSocket server on the backend and WebSocket clients on the front end. The server listens for incoming WebSocket connections, while the client initiates a WebSocket handshake and communicates with the server using JavaScript's WebSocket API.
For the backend, we'll use Node.js and the ws library to create a WebSocket server. The ws library facilitates WebSocket connection management, message handling, and broadcasting to connected clients.
On the front end, we'll instantiate a WebSocket object using the WebSocket constructor. We'll utilize the onopen, onmessage, and onclose events to manage various operations, and employ the send() method to transmit messages to the server."
Syntax (Client side):
const socket = new WebSocket('ws://localhost:8080');
socket.onopen = function(event) {
// Handle connection open
};
socket.onmessage = function(event) {
// Handle received message
};
socket.onclose = function(event) {
// Handle connection close
};
function sendMessage(message) {
socket.send(message);
}
Syntax (Server-side Node.js):
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
// Handle incoming message
});
ws.on('close', function() {
// Handle connection close
});
});
Steps to create Application
Step 1: Create a NodeJS application using the following command:
npm init
Step 2: Install required Dependencies:
npm i ws
The updated dependencies in package.json file will look like:
"dependencies": {
"ws": "^8.16.0"
}
Example: The Below example is demonstrating the use of WebSocket.
index.js (project root folder)
JavaScript
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) {
console.log('Client connected');
ws.on('message', function incoming(message) {
console.log('Received: %s', message);
ws.send(`${message}`);
});
ws.on('close', function () {
console.log('Client disconnected');
});
});
index.html
HTML
<!-- File path: index.html (project root folder) -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebSocket Client</title>
<style>
h1 {
color: green;
}
.container {
margin: 10px;
}
</style>
</head>
<body>
<h1>WebSocket Example</h1>
<div class="container">
<label>Send Message to Server:</label> <br><br>
<input type="text" id="messageInput">
<button onclick="sendMessage()">Send</button>
<div id="output"></div>
</div>
<script>
// Create a WebSocket instance
// and connect to the server
const socket = new WebSocket('ws://localhost:8080');
// Event listener for when
//the WebSocket connection is opened
socket.onopen = function (event) {
// Alert the user that they are
// connected to the WebSocket server
alert('You are Connected to WebSocket Server');
};
// Event listener for when a message
// is received from the server
socket.onmessage = function (event) {
// Get the output div element
const outputDiv = document
.getElementById('output');
// Append a paragraph with the
// received message to the output div
outputDiv
.innerHTML += `<p>Received <b>"${event.data}"</b> from server.</p>`;
};
// Event listener for when the
// WebSocket connection is closed
socket.onclose = function (event) {
// Log a message when disconnected
// from the WebSocket server
console.log('Disconnected from WebSocket server');
};
// Function to send a message
// to the WebSocket server
function sendMessage() {
// Get the message input element
const messageInput = document
.getElementById('messageInput');
// Get the value of
// the message input
const message = messageInput.value;
// Send the message to
// the WebSocket server
socket.send(message);
// Clear the message input
messageInput.value = '';
}
</script>
</body>
</html>
To launch the application, execute the following command in your terminal:
node index.js
Then, open the `index.html` file in your web browser."
Output:

Server side output:

Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read