The Wayback Machine - https://web.archive.org/web/20240922101316/https://www.geeksforgeeks.org/how-to-create-a-websocket-connection-in-javascript/
Open In App

How to Create a WebSocket Connection in JavaScript ?

Last Updated : 21 Mar, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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:

Node

Server side output:

websocket-server



Similar Reads

MQTT vs WebSocket
When one first looks at MQTT and WebSocket, this looks the same. As in both cases, once the connection is established, then the user can send anything between the client and the server. Also, both are full duplexes which means that both client and the server are speaking and listening at real time. MQTT is message based while WebSocket is session b
2 min read
HTTP headers | Sec-WebSocket-Accept
The HTTP headers are used for passing additional information with an HTTP request or response between the client and the server. They are grouped as general-headers, request-headers, response-headers, entity-headers. The Sec-WebSocket-Accept header falls under the response-type headers category. It is used by the server to intimate the client that
2 min read
What is the use of WebSocket API ?
API stands for Application Programming Interface. API can be defined as a predefined set of instructions that describes how different applications can communicate with one another. So one can think of API as a middleman for transferring data between a web server and the application. Every app is using some kind of API to transfer data between appli
3 min read
How to Send WebSocket Requests with Postman ?
This article will show how to send WebSocket requests in Postman. Postman is a popular collaborative platform for API development. It offers different tools for designing, debugging, and testing an API, making it more efficient. WebSocket is an advanced technology used for real-time bidirectional communication between clients and servers. Postman a
3 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 effectively. This guide will walk you through the ess
10 min read
How to Test WebSocket APIs With Postman?
WebSocket is a communication protocol that provides full-duplex communication channels over a single, long-lived connection between clients and servers. Unlike HTTP, which is a request-response protocol, WebSocket allows both the client and server to send messages to each other independently at any time, enabling real-time data transfer. Table of C
4 min read
How to detect the Internet connection is offline or not using JavaScript?
In some cases, it is necessary to determine whether the browser is online or offline before performing a required task. Many developers use AJAX to determine the connection status of the browser (online or offline) by sending a request to the server. However, this is not a good method for determining the state of the browser because it requires ban
1 min read
How to accept all pending connection requests on LinkedIn using JavaScript ?
Many times we get a lot of connection requests over LinkedIn, and we want to accept all of them but for that, we have to click the accept button for each connection request. With the help of the following way, we can accept all of them at once using JavaScript helping us to save our time and effort. Approach: Make a variable connection that points
2 min read
Mongoose Schema Connection.prototype.set() API
The Connection.prototype.set() method of the Mongoose API is used on the Connection object. It allows us to set the value for keys in the options object. We can provide the key and its value to the set() method in order to set the options for the connection object. Let us understand the set() method using an example. Syntax: connection.set( &lt;key
2 min read
Database Connection and Queries in Codeigniter
To retrieve data from database we always need to connect our project with database. We will see how to connect database in codeignitor and how to run queries in it. In config folder we can find database.php file to connect with database. Mention the details as per shown image below. database.php In the above image, we need to define the username, p
3 min read
HTTP headers | Connection
The HTTP Connection header is a general type header that allows the sender or client to specify options that are desired for that particular connection. Instead of opening a new connection for every single request/response, Connection helps in sending or receiving multiple HTTP requests/responses using a single TCP connection. It also controls whet
2 min read
Laravel | MySQL Database Connection
The database is an important element in any application. Laravel by default provides the support of MySQL. MySQL is a well known, open-source RDBMS (Relational Database Management System). Process for Connecting to the Database: Step 1: First we have to create a database. So, we will start Apache and MySQL server form XAMPP Control Panel. Step 2: O
3 min read
Node.js Http2ServerResponse.connection Method
The Http2ServerResponse.connection is an inbuilt application programming interface of class Http2ServerRequest within the http2 module which is used to get the reference of the net.Socket object. Syntax: const response.connection Parameters: This method does not accept any argument as a parameter. Return Value: This method returns the reference of
3 min read
Node.js http.ServerResponse.connection Method
The httpServerResponse.connection is an inbuilt application programming interface of class Server Response within http module which is used to get the response socket of this HTTP connection. Syntax: response.connection Parameters: This method does not accept any argument as a parameter. Return Value: This method returns the response socket of this
2 min read
Node.js http.ClientRequest.connection Property
The http.ClientRequest.connection is an inbuilt application programming interface of class ClientRequest within the HTTP module which is used to get the reference of underlying client request socket. Syntax: const request.connectionParameters: It does not accept any argument as the parameter. Return Value: It does not return any value. Example 1: F
2 min read
Mongoose Schema API Connection.prototype.modelNames()
The Connection.prototype.modelNames() method of the Mongoose API is used on the Connection object. It allows us to get information about all the models that have been created using a particular connection object. Syntax: connection.modelNames( );Parameters: This method does not accept any parameter.Return Value: This method returns an array. Return
2 min read
How to save connection result in a variable in Node.js ?
We are going to use the query function in MySQL library in node.js that will return our output as expected. Using this approach, we can save connection result in a variable in Node.js. Setting up environment and Execution: Step 1: Initialize node project using the following command. npm init Step 2: Turn on MySQL Database Step 3: After creating the
1 min read
How to get a dialog box if there is no internet connection using jQuery ?
In this article, we will see how to check the internet connection using jQuery. We will be using navigator.onLine which will return true if an internet connection is available otherwise it will return false. Syntax: navigator.onLine Returns: True: If the internet connection is available.False: If the internet connection is not available. Example 1:
2 min read
Mongoose Schema Connection.prototype.asPromise() API
The Mongoose Schema API Connection.prototype.asPromise() method of the Mongoose API is used on the Connection object. It allows us to get the result as a promise if the connection to the MongoDB is successfully connected which means the promise is resolved else the promise is rejected. Let us understand the asPromise() method using an example. Synt
2 min read
How to make a connection with MySQL server using PHP ?
MySQL is a widely used database management system that may be used to power a wide range of projects. One of its main selling features is its capacity to manage large amounts of data without breaking a sweat. There are two approaches that can be used to connect MySQL and PHP code, which are mentioned below. PDO (PHP Data Objects)MySQLi extension Le
3 min read
How to wait for MongoDB connection to be made before creating HTTP server in Node.js?
Connecting your server to is a database a very crucial task in back-end development as the database is the location where the user-provided data will be stored until further action is taken. If we fail to connect to the database before creating the server, whatever data is being processed by the server will not get stored in the database. So, as a
3 min read
How to establish connection between Node.js ans Redis ?
NodeJS is an open-source back-end JavaScript runtime environment for executing JavaScript outside the browser. It is widely used for server-side development in many companies. Redis is a popular in-memory key-value database. Unlike traditional databases that run on a computer's hard disk and store all of their data on disk, Redis runs inside of a s
3 min read
What are the disadvantages of using persistent connection in PDO ?
In PDO, a connection to the database can be persistent or non-persistent. Persistent connections make using the attribute PDO::ATTR_PERSISTENT. Persistent connections do not close when the script ends, but they are cached and can be reused when a requested persistent connection is identical to the existing connection. When a connection is requested
3 min read
Mongoose Schema Connection.prototype.dropCollection() API
The Connection.prototype.dropCollection() method of the Mongoose API is used on the Connection object. It allows us to delete particular collections from the MongoDB database. With the help of this method, we can remove any collection from the database along with all the documents and indexes associated with it. Let us understand dropCollection() m
2 min read
Mongoose Schema Connection.prototype.useDb() API
The Connection.prototype.useDb() method of the Mongoose API is used on the Connection object. It allows us to change the current working database. It is used to switch between databases using the same connection pool. Let us understand useDb() method using an example. Syntax: connection.useDb( &lt;db_name&gt; ); Parameters: This method accepts two
2 min read
Mongoose Schema Connection.prototype.dropDatabase() API
The Connection.prototype.dropDatabase() method of the Mongoose API is used on the Connection object. It allows us to delete particular database from MongoDB. Along with the database it will delete collection, documents, and index related data as well. Let us understand dropDatabase() method using an example. Syntax: connection.dropDatabase( &lt;cal
2 min read
Mongoose Schema Connection.prototype.id API
The Mongoose Schema API Connection.prototype.id of the Mongoose API is used on the Connection objects. It allows us to check how many connections does connection object poses. It is used to debug the connection object when we have multiple connections pointing to one single connection reference. Let us understand the id property using an example. S
2 min read
Mongoose Schema Connection.prototype.model() Function
The Mongoose Schema API Connection.prototype.model() of the Mongoose API is used on the Connection objects. It allows us to define new model in the MongoDB database for particular connection object. It is used to define and retrieve models in and from the database. Let us understand models() method using an example. Syntax: connectionObject.model(
3 min read
Mongoose Schema Connection.prototype.models API
Mongoose Schema API Connection.prototype.models of the Mongoose API is used on the Connection objects. It allows us to get list of all the models we have defined using connection.model() on a particular connection object. Let us understand the models property using an example. Syntax: connectionObject.models; Parameters: This property does not acce
2 min read
Mongoose Schema Connection.prototype.collections API
The Mongoose Schema API Connection.prototype.collections property of the Mongoose API is used on the Connection object. It allows us to get the details about the collections that are associated with the connection object. Each connection object poses how many collections that information we will get in the hashed format. Let us understand the colle
2 min read