WebSocket
networking web protocol advanced
What is WebSocket?
WebSocket is a technology that lets websites and servers have a continuous conversation.
Unlike regular web requests where you have to ask for information each time, WebSockets create a persistent connection that stays open, allowing both sides to send messages whenever they need to.
Simple Analogy
Think of WebSockets like different ways of communicating:
- Regular Web Requests (HTTP): Like sending letters through the mail. Each time you want to communicate, you have to write a letter, put it in an envelope, mail it, and wait for a response. This is slow and inefficient if you need to exchange lots of information quickly.
- WebSockets: Like having a phone call. Once the call is established, both parties can speak whenever they need to without having to redial the number each time. The connection stays open until someone hangs up.
Key Concepts
- Persistent Connection: Unlike HTTP which closes after each request/response, WebSockets stay open until explicitly closed
- Full-Duplex Communication: Both client and server can send messages independently at any time
- Low Latency: Reduced overhead results in faster communication, essential for real-time applications
- Efficient: Less bandwidth usage compared to polling or long-polling HTTP requests
- Upgrade Mechanism: WebSocket connections start as HTTP requests and then “upgrade” to WebSocket protocol
Example
// Client-side WebSocket implementation
const socket = new WebSocket('ws://example.com/socket');
// Connection opened
socket.addEventListener('open', (event) => {
socket.send('Hello Server!');
});
// Listen for messages
socket.addEventListener('message', (event) => {
console.log('Message from server:', event.data);
});
// Connection closed
socket.addEventListener('close', (event) => {
console.log('Connection closed');
});