What is Web Socket and Web Socket Tutorial

In the ever-evolving world of web technologies, real-time communication has become a cornerstone of modern web applications. From live chat applications to real-time data feeds, the need for instantaneous communication between clients and servers is more prominent than ever. This is where WebSocket comes into play. WebSocket is a protocol that provides full-duplex communication channels over a single, long-lived connection. It is designed to facilitate real-time interaction between a web browser and a web server, and it is an essential technology for building dynamic, interactive web applications.

What is WebSocket?

WebSocket is a communication protocol that was standardized by the IETF as RFC 6455 in 2011. It operates over a TCP (Transmission Control Protocol) connection and is designed to be used by web applications. Unlike traditional HTTP, which follows a request-response model, WebSocket allows for a persistent connection between the client and server. This persistent connection enables both parties to send and receive data at any time, making it an ideal solution for applications that require real-time communication.

What is Web Socket
What is Web Socket

The WebSocket protocol is initiated by a handshake between the client and the server. This handshake is similar to the initial HTTP request, but it includes an "Upgrade" header that indicates the desire to establish a WebSocket connection. Once the handshake is complete, the connection is established and remains open until either the client or server decides to close it.

What Exactly WebSockets Do

WebSockets are designed to enable real-time, bi-directional communication between clients and servers. This means that both the client and the server can send and receive messages independently of each other. This is in contrast to the traditional HTTP model, where the client must initiate all communication by sending a request to the server.

Here are some key functionalities that WebSockets provide:

Low Latency Communication: WebSockets reduce the latency of communication between the client and server by eliminating the need for repeated HTTP requests. Once the connection is established, data can be sent and received with minimal delay.

Full-Duplex Communication: WebSockets allow for full-duplex communication, meaning that both the client and server can send and receive messages simultaneously. This is essential for real-time applications where timely updates are crucial.

Efficient Data Transfer: WebSockets use a binary framing protocol that is more efficient than traditional HTTP headers. This reduces the overhead of each message, making WebSocket communication more efficient for small, frequent updates.

Persistent Connection: WebSockets maintain a persistent connection between the client and server, which reduces the overhead associated with establishing and tearing down connections. This is particularly useful for applications that require long-lived connections.

How Web Sockets are Different from HTTP

WebSockets and HTTP are both protocols used for communication between clients and servers, but they have several key differences:

1. Connection Model: HTTP follows a request-response model, where the client initiates a request and the server sends a response. In contrast, WebSockets establish a persistent connection that allows for bi-directional communication without the need for repeated requests.

2. Latency: WebSockets provide lower latency communication compared to HTTP. This is because WebSockets eliminate the need for repeated requests and responses, allowing for more efficient data transfer.

3. Overhead: WebSockets have lower overhead compared to HTTP. This is due to the more efficient binary framing protocol used by WebSockets, which reduces the amount of data that needs to be sent with each message.

4. Statefulness: WebSockets maintain a persistent connection between the client and server, which allows for stateful communication. HTTP, on the other hand, is a stateless protocol, meaning that each request is independent and does not maintain any information about previous requests.

Client Server Architecture
http Client Server

Use Cases: WebSockets are ideal for real-time applications that require low latency and bi-directional communication, such as live chat applications, real-time data feeds, and online gaming. HTTP is more suited for traditional web applications that do not require real-time interaction.


Feature WebSocket HTTP
Communication Full-duplex communication Half-duplex communication
Connection Persistent connection Connection is re-established for each request/response
Latency Low latency due to reduced overhead Higher latency due to overhead of setting up connections
Data Transfer Real-time data transfer Typically request-response model
Protocol WS:// (or WSS:// for secure) HTTP:// (or HTTPS:// for secure)
State Maintains stateful connection Stateless, each request is independent
Use Cases Real-time applications like chat apps, live sports updates Traditional web browsing, form submissions, API calls
Data Frames Binary and text frames Text-based protocol
Overhead Lower overhead after initial handshake Higher overhead for each request/response cycle
Security Uses WSS (WebSocket Secure) with TLS for secure communication Uses HTTPS with SSL/TLS for secure communication
Server Push Allows server to push data to client Server cannot push data without client request
Efficiency More efficient for frequent, real-time data exchanges Less efficient for frequent, real-time data exchanges
Example Use Online gaming, live chats, real-time notifications Browsing web pages, submitting forms, downloading files

How to Build a WebSocket Server: Step-by-Step Example

Building a WebSocket server can seem daunting, but with the right tools and a clear understanding of the process, it can be quite straightforward. In this example, we will build a simple WebSocket server using Node.js and the popular ws library.

Web Socket
Web Socket

Step 1: Setting Up the Project

First, let's create a new directory for our project and initialize it with npm (Node Package Manager).

mkdir websocket-server
cd websocket-server
npm init -y

This will create a package.json file in your project directory.

Step 2: Installing Dependencies

Next, we need to install the ws library, which will help us set up the WebSocket server.

npm install ws

Step 3: Creating the WebSocket Server

Create a new file called server.js in your project directory. This file will contain the code for our WebSocket server.

const WebSocket = require('ws');

// Create a new WebSocket server
const wss = new WebSocket.Server({ port: 8080 });

// Event listener for new connections
wss.on('connection', (ws) => {
    console.log('New client connected');

    // Event listener for incoming messages
    ws.on('message', (message) => {
        console.log(`Received message: ${message}`);

        // Echo the message back to the client
        ws.send(`You said: ${message}`);
    });

    // Event listener for client disconnections
    ws.on('close', () => {
        console.log('Client disconnected');
    });
});

console.log('WebSocket server is running on ws://localhost:8080');

Step 4: Running the Server

With the server code in place, we can now run our WebSocket server.

node server.js

You should see the message "WebSocket server is running on ws://localhost:8080" in your terminal. This indicates that the server is up and running.

Step 5: Testing the WebSocket Server

To test our WebSocket server, we can use a WebSocket client. There are several ways to do this, but one of the easiest methods is to use a web browser's developer console.

Open a new browser window and navigate to any web page. Open the developer console (usually by pressing F12 or right-clicking on the page and selecting "Inspect"). In the console, enter the following JavaScript code to create a WebSocket client:

const ws = new WebSocket('ws://localhost:8080');

// Event listener for when the connection is opened
ws.onopen = () => {
    console.log('Connected to the WebSocket server');

    // Send a message to the server
    ws.send('Hello, server!');
};

// Event listener for when a message is received from the server
ws.onmessage = (event) => {
    console.log(`Received message from server: ${event.data}`);
};

// Event listener for when the connection is closed
ws.onclose = () => {
    console.log('Disconnected from the WebSocket server');
};

You should see the messages "Connected to the WebSocket server" and "Received message from server: You said: Hello, server!" in the console. This indicates that the client successfully connected to the server, sent a message, and received a response.

Step 6: Enhancing the WebSocket Server

Now that we have a basic WebSocket server up and running, let's enhance it with some additional features. For example, we can broadcast messages to all connected clients.

Update the server.js file as follows:

const WebSocket = require('ws');

// Create a new WebSocket server
const wss = new WebSocket.Server({ port: 8080 });

// Event listener for new connections
wss.on('connection', (ws) => {
    console.log('New client connected');

    // Event listener for incoming messages
    ws.on('message', (message) => {
        console.log(`Received message: ${message}`);

        // Broadcast the message to all clients
        wss.clients.forEach((client) => {
            if (client.readyState === WebSocket.OPEN) {
                client.send(`Broadcast: ${message}`);
            }
        });
    });

    // Event listener for client disconnections
    ws.on('close', () => {
        console.log('Client disconnected');
    });
});

console.log('WebSocket server is running on ws://localhost:8080');

With this enhancement, the server will broadcast any received message to all connected clients.

Step 7: Running the Enhanced Server

Run the enhanced server by executing the following command:

node server.js

Open multiple browser windows and run the WebSocket client code in each. When you send a message from one client, you should see the message broadcast to all connected clients.

WebSockets are a powerful tool for enabling real-time, bi-directional communication between clients and servers. They offer several advantages over traditional HTTP, including lower latency, reduced overhead, and persistent connections. By following the steps outlined in this guide, you can build your own WebSocket server and start leveraging the power of real-time communication in your web applications.

Whether you're building a live chat application, a real-time data feed, or an online gaming platform, WebSockets provide the foundation you need to create dynamic, interactive experiences for your users.

Most Asked Questions

What is Web Socket in Short?

Web Socket is a communication protocol that provides full-duplex communication channels over a single TCP connection. It is designed to be implemented in web browsers and web servers, allowing for real-time, bidirectional communication between client and server.

What is Web Socket in node js?

In Node.js, Web Socket is used to create real-time applications by enabling bidirectional communication between the client and the server. The 'ws' library is commonly used to implement Web Socket functionality in Node.js, allowing developers to build scalable and efficient real-time web applications.

What is Web Socket Server?

A Web Socket Server is a server that implements the Web Socket protocol to handle Web Socket connections from clients. It facilitates real-time, bidirectional communication by maintaining open connections with clients, enabling instant data exchange without the need for repeated HTTP requests.

Shubhadip Bhowmik

I am a B.C.A student at Chandigarh University, with a passion for technology. I am an Android and Frontend Web Developer. I write blogs, design UI/Mockups, and Contributing to open-source projects. youtube github linkedin emailm

Post a Comment (0)
Previous Post Next Post