File size: 4,119 Bytes
a7d7463
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
# WebSocket Protocol

## What is WebSocket?

WebSocket provides full-duplex communication channels over a single TCP connection. Unlike HTTP, WebSocket allows real-time bidirectional communication.

## Connection Flow

```
Client                          Server
  │                              │
  │──── HTTP Upgrade Request ────▶│
  │        Upgrade: websocket     │
  │                              │
  │◀─── HTTP 101 Switching -------│
  │        Protocol: ws          │
  │                              │
  │◀═════ WebSocket Open ═════════▶│
  │                              │
  │◀═════ Messages ══════════════▶│
  │                              │
  │◀═════ Connection Close ═══════▶│
```

## WebSocket Headers

### Upgrade Request
```
GET /ws HTTP/1.1
Host: api.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
```

### Server Response
```
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
```

## Implementation Examples

### Server (Node.js + ws)
```javascript
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.toString());
        ws.send('Echo: ' + message);
    });
    
    ws.on('close', () => {
        console.log('Client disconnected');
    });
    
    // Send periodic message
    const interval = setInterval(() => {
        ws.send('Ping: ' + Date.now());
    }, 30000);
    
    ws.on('close', () => clearInterval(interval));
});
```

### Client (Browser)
```javascript
const ws = new WebSocket('ws://localhost:8080');

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

ws.onmessage = (event) => {
    console.log('Received:', event.data);
};

ws.onerror = (error) => {
    console.error('WebSocket error:', error);
};

ws.onclose = () => {
    console.log('Disconnected');
};
```

### Client (Python)
```python
import asyncio
import websockets

async def main():
    async with websockets.connect('ws://localhost:8080') as ws:
        await ws.send('Hello Server!')
        response = await ws.recv()
        print(f"Received: {response}")

asyncio.run(main())
```

## Socket.IO (Higher Level)

### Server
```javascript
const { Server } = require('socket.io');
const io = new Server(3000, {
    cors: { origin: '*' }
});

io.on('connection', (socket) => {
    console.log('User connected:', socket.id);
    
    socket.on('message', (data) => {
        console.log('Message:', data);
        io.emit('message', data);
    });
    
    socket.on('disconnect', () => {
        console.log('User disconnected');
    });
    
    socket.on('join-room', (room) => {
        socket.join(room);
        socket.to(room).emit('user-joined', socket.id);
    });
});
```

### Client
```javascript
import { io } from 'socket.io-client';

const socket = io('http://localhost:3000');

socket.on('connect', () => {
    console.log('Connected:', socket.id);
    socket.emit('message', 'Hello everyone!');
});

socket.on('message', (data) => {
    console.log('Received:', data);
});
```

## WebSocket vs HTTP

| Aspect | WebSocket | HTTP |
|--------|----------|------|
| Connection | Persistent | Request-Response |
| Direction | Bidirectional | Client → Server |
| Overhead | Low (after handshake) | High (headers each request) |
| Use Case | Real-time apps | REST APIs, simple requests |
| Browser Support | Modern browsers | All browsers |

## Best Practices

1. **Heartbeat/Ping-Pong** - Keep connections alive
2. **Reconnection Logic** - Handle connection drops
3. **Message Queueing** - Queue messages during disconnect
4. **Authentication** - Validate on connection
5. **Rate Limiting** - Prevent abuse
6. **Compression** - Consider permessage-deflate