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
How to connect to an API in JavaScript ?
An API or Application Programming Interface is an intermediary which carries request/response data between the endpoints of a channel. We can visualize an analogy of API to that of a waiter in a restaurant. A typical waiter in a restaurant would welcome you and ask for your order. He/She confirms th
5 min read
How to Secure your WebSocket Connections?
WebSockets are a powerful technology that enables interactive communication between a client and server. They are increasingly used in real-time applications such as live chats, gaming, and financial trading platforms. However, with this power comes the responsibility to secure these connections eff
10 min read
How to Create a Socket at a Specific Port in Java?
A socket is one end-point of a two-way communication link between two programs running on the network. Socket classes are used to represent the connection between a client program and a server program. Socket Programming, us basically client-server programming where a socket is used as a link betwee
3 min read
How to connect SQL Server database from JavaScript in the browser ?
There is no common way to connect to the SQL Server database from a JavaScript client, every browser has its own API and packages to connect to SQL Server. For example, in the Windows operating system, Internet Explorer has a class name called ActiveXObject which is used to create instances of OLE A
4 min read
Real-time chat application in JavaScript
A real-time chat application is a software application that enables users to exchange messages and communicate with each other in real-time. It allows individuals or groups to have conversations, share information, and collaborate instantly over the Internet.Real-time chat applications are designed
6 min read
How to Create a Chat App Using socket.io in NodeJS?
Socket.io is a JavaScript library that enables real-time, bidirectional, event-based communication between the client and server. It works on top of WebSocket but provides additional features like automatic reconnection, broadcasting, and fallback options.What We Are Going to Create?In this article,
5 min read
How to Design a Weather Bot in Telegram using JavaScript ?
Telegram bot can be used to know the complete weather details of any city, state, a country without going using another application. Telegram provides a bunch of API methods to perform different functions. You can use telegram bot API to create a Chatbot that returns weather-based information about
3 min read
How to Make GET call to an API using Axios in JavaScript?
Axios is a promise-based HTTP client designed for Node.js and browsers. With Axios, we can easily send asynchronous HTTP requests to REST APIs and perform create, read, update and delete operations. It is an open-source collaboration project hosted on GitHub. It can be imported in plain JavaScript o
3 min read
Load Balancing for WebSockets in Spring Boot
WebSocket provides full-duplex communication channels over a single TCP connection, crucial for real-time applications like chat, gaming, and live data streaming. Load balancing WebSocket connections in Spring Boot ensures optimal performance and scalability by distributing incoming requests among m
4 min read
Node.js socket.connect() Method
The socket.connect() method is an inbuilt application programming interface of class Socket within dgram module which is used to connect the particular server to a particular port and address. Syntax: const socket.connect(port[, address][, callback]) Parameters: This method accepts the following par
3 min read