Junior
What are web sockets?
sobes.tech AI
Answer from AI
WebSockets are a protocol for bidirectional communication over a single TCP connection, allowing real-time data exchange between browser and server.
Main differences from traditional HTTP requests:
- Bidirectional communication: Server can send data to client without a prior request.
- Single connection: A long-lived connection is established, reducing overhead compared to creating new connections for each data exchange (as in HTTP).
- Reduced latency: Less time spent on connection setup, headers, and short request/response cycles.
How it works:
- Handshake: Browser sends a special HTTP request to the server with headers
Upgrade: websocketandConnection: Upgrade. - Connection establishment: If supported, server responds with
101 Switching Protocols, and the connection switches to WebSocket protocol. - Data transfer: Both sides can freely exchange messages in both directions at any time.
Use cases:
- Online games
- Chat and messaging apps
- Real-time data updates (quotes, news)
- Collaborative tools
Advantages:
- Low latency
- Efficient resource use (less overhead)
- Real-time bidirectional communication
Disadvantages:
- Requires support on client (browser) and server sides.
- More complex implementation than simple HTTP requests.
Client-side example in JavaScript:
// Create WebSocket
const socket = new WebSocket('wss://example.com/websocket');
// On open
socket.onopen = function(event) {
console.log('Connection established');
socket.send('Hello, server!'); // Send message
};
// On message
socket.onmessage = function(event) {
console.log('Received message: ' + event.data);
};
// On close
socket.onclose = function(event) {
if (event.wasClean) {
console.log(`Closed cleanly, code=${event.code} reason=${event.reason}`);
} else {
console.log('Connection interrupted');
}
};
// On error
socket.onerror = function(error) {
console.error(`WebSocket error: ${error}`);
};
// To close
// socket.close();