# WebSocket

### **What is WebSocket?**

WebSocket is a communication protocol that provides **full-duplex**, **real-time** communication between a client and a server over a **single TCP connection**. Unlike traditional HTTP, which follows a **request-response** model, WebSockets enable continuous **bidirectional** communication, making them ideal for **chat applications, live notifications, gaming, and stock market updates**.

### **How WebSockets Work**

1. **Handshake** – The client sends an **HTTP request** to upgrade the connection to WebSocket.
2. **Connection Establishment** – The server accepts the request, and both establish a persistent WebSocket connection.
3. **Bidirectional Communication** – The client and server can now send messages anytime without waiting for a response.
4. **Connection Closure** – Either side can close the connection when needed.

### **WebSocket Architecture**

* **Client** – A web browser or app initiating a WebSocket connection.
* **WebSocket Server** – Manages connections and routes messages.
* **Message Transport** – The WebSocket protocol sends messages over a single connection.

### **WebSocket Example (Node.js & JavaScript)**

Let's create a **WebSocket server** and a **WebSocket client**.

#### **1. Install WebSocket Library**

Run the following command to install WebSocket support:.

```sh
npm install ws

```

2. Create a WebSocket Server (Node.js)

```javascript
const WebSocket = require('ws');

const server = new WebSocket.Server({ port: 8080 });

server.on('connection', (socket) => {
    console.log('New client connected');

    socket.on('message', (message) => {
        console.log(`Received: ${message}`);
        socket.send(`Server received: ${message}`);
    });

    socket.on('close', () => {
        console.log('Client disconnected');
    });
});

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

```

3. Create a WebSocket Client (Browser JavaScript)

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

socket.onopen = () => {
    console.log('Connected to WebSocket server');
    socket.send('Hello, Server!');
};

socket.onmessage = (event) => {
    console.log(`Message from server: ${event.data}`);
};

socket.onclose = () => {
    console.log('Disconnected from WebSocket server');
};

```

### WebSocket Events:

<table><thead><tr><th width="176.15350341796875">Event</th><th>Description</th></tr></thead><tbody><tr><td>onopen</td><td>Triggered when the WebSocket connection is established.</td></tr><tr><td>onmessage</td><td>Triggered when a message is received from the server.</td></tr><tr><td>onerror</td><td>Triggered when an error occurs.</td></tr><tr><td>onclose</td><td>Triggered when the connection is closed.</td></tr></tbody></table>

### **WebSocket Use Cases**

* **Live Chat Applications** – Instant messaging with real-time updates.
* **Stock Market Feeds** – Live updates of stock prices.
* **Online Gaming** – Multiplayer games with real-time interactions.
* **Live Sports Scores** – Streaming real-time game updates.
* **Collaboration Tools** – Google Docs-style real-time editing.

### **Disadvantages of WebSockets**

* **Firewall Issues** – Some corporate networks block WebSocket connections.
* **Scalability** – Managing multiple open WebSocket connections can be resource-intensive.
* **Complexity** – More difficult to implement than traditional HTTP requests.

### **When to Use WebSockets?**

* **Need real-time updates** (Chat apps, stock tickers, notifications).
* **Frequent two-way communication** (Gaming, live streaming).
* **Reduce latency** (Instant response without polling the server).

### **Conclusion**

WebSockets provide an efficient, low-latency communication channel for real-time applications. They outperform HTTP when **continuous, bidirectional** data flow is required.
