C Programs Tutorials | IT Developer
IT Developer

HTML Web Sockets



Share with a Friend

Introduction

WebSockets is a modern protocol that provides a full-duplex communication channel over a single TCP connection. Unlike traditional HTTP communication, where the client has to request information from the server, WebSockets enable real-time, bi-directional communication between the client and the server. This makes WebSockets ideal for applications that require instant updates, such as chat applications, gaming, live notifications, or collaborative editing tools.


How WebSockets Work

  1. Connection Establishment:

    1. The WebSocket protocol starts with an HTTP handshake, where the client requests to establish a WebSocket connection with the server.

    2. Once the handshake is complete, the connection upgrades to a WebSocket.

  2. Full-Duplex Communication:

    1. After the connection is established, both the client and the server can send and receive messages simultaneously without requiring repeated requests.

  3. Persistent Connection:

    1. The connection remains open until explicitly closed by either the client or the server.


Features of WebSockets

  1. Real-Time Communication: Data is sent and received instantly between the server and client.

  2. Low Latency: Avoids the overhead of HTTP requests and responses, making it faster than traditional polling or long-polling.

  3. Bidirectional: Both the server and client can independently send messages to each other.

  4. Persistent Connection: The connection stays open, reducing the need for frequent reconnections.


WebSocket vs. HTTP

Feature HTTP WebSocket
Communication Request-Response (Half-Duplex) Full-Duplex
Overhead High (Repeated requests) Low (Single connection)
Connection Stateless Persistent
Use Case Standard web interactions Real-time applications

When to Use WebSockets

WebSockets are most suitable for scenarios that require real-time updates or continuous communication, such as:

  1. Chat applications

  2. Online gaming

  3. Stock price updates

  4. Real-time collaboration (e.g., Google Docs)

  5. Live notifications

  6. IoT communication


How to Use WebSockets

1. Setting Up a WebSocket Connection

In a client-side JavaScript application, you can create a WebSocket connection using the WebSocket API.

Client-Side Example:

// Create a WebSocket connection const socket = new WebSocket("ws://example.com/socket"); // Open event: Triggered when the connection is established socket.onopen = function () { console.log("WebSocket connection established"); // Send a message to the server socket.send("Hello, Server!"); }; // Message event: Triggered when a message is received from the server socket.onmessage = function (event) { console.log("Message from server:", event.data); }; // Error event: Triggered when there's an error with the WebSocket socket.onerror = function (error) { console.error("WebSocket error:", error); }; // Close event: Triggered when the WebSocket connection is closed socket.onclose = function () { console.log("WebSocket connection closed"); };

2. Server-Side WebSocket Implementation

On the server side, frameworks like Node.js with the ws library can be used to handle WebSocket connections.

Server-Side Example (Node.js):

const WebSocket = require('ws'); // Create a WebSocket server const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', (ws) => { console.log("Client connected"); // Listen for messages from the client ws.on('message', (message) => { console.log("Received from client:", message); // Send a response back to the client ws.send("Message received: " + message); }); // Handle connection close ws.on('close', () => { console.log("Client disconnected"); }); });

Key WebSocket Methods and Events

Methods

  1. new WebSocket(url):

    1. Creates a new WebSocket object.

    2. Example: const socket = new WebSocket("ws://example.com");

  2. send(data):

    1. Sends data to the server.

    2. Example: socket.send("Hello, server!");

  3. close():

    1. Closes the WebSocket connection.

    2. Example: socket.close();


Events

  1. onopen: Triggered when the connection is successfully established.

  2. onmessage: Triggered when the client receives a message from the server.

  3. onerror: Triggered when there's an error with the connection.

  4. onclose: Triggered when the connection is closed.


WebSocket Communication Example

Client-Side HTML + JavaScript

<!DOCTYPE html> <html> <head> <title>WebSocket Example</title> </head> <body> <h1>WebSocket Example</h1> <button onclick="sendMessage()">Send Message</button> <div id="messages"></div> <script> const socket = new WebSocket("ws://localhost:8080"); socket.onopen = function () { console.log("Connected to WebSocket server"); }; socket.onmessage = function (event) { const messagesDiv = document.getElementById("messages"); messagesDiv.innerHTML += ${<p>Server: event.data</p>}; }; function sendMessage() { socket.send("Hello from the client!"); } </script> </body> </html>

Server-Side (Node.js)

const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', (ws) => { console.log("Client connected"); ws.on('message', (message) => { console.log("Received:", message); ws.send("Hello from the server!"); }); });

Advantages of WebSockets

  1. Real-Time Updates:

    1. Perfect for instant communication.

  2. Efficient Use of Resources:

    1. Single connection reduces overhead and latency.

  3. Cross-Platform:

    1. Supported by all major browsers and frameworks.


Limitations of WebSockets

  1. Firewall and Proxy Issues:

    1. May face connection issues with restrictive firewalls or proxies.

  2. Complex Implementation:

    1. Requires more setup and maintenance than standard HTTP requests.

  3. Security Concerns:

    1. Must use wss:// for encrypted connections (WebSocket Secure).


Conclusion

WebSockets are a powerful tool for building interactive and real-time web applications. By enabling full-duplex communication, WebSockets ensure a seamless exchange of data between the client and the server. Whether you’re building a chat app, a stock ticker, or a multiplayer game, WebSockets can significantly enhance the user experience.