WebSocket is a protocol that enables full-duplex, bidirectional communication between a client and a server over a single TCP connection. It's designed for real-time, event-driven applications such as chat systems, live updates, and gaming.
The WebSocket connection starts with an HTTP upgrade request:
GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Origin: http://example.com
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13
Server response:
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Sec-WebSocket-Protocol: chat
ws://
or wss://
(for secure WebSocket) URL schemeThe WebSocket API provides a simple interface for creating and managing WebSocket connections.
const socket = new WebSocket('ws://example.com/socketserver');
Example using Node.js and the ws
library:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
ws.send('Welcome to the WebSocket server!');
});
const socket = new WebSocket('ws://localhost:8080');
socket.addEventListener('open', function (event) {
socket.send('Hello Server!');
});
socket.addEventListener('message', function (event) {
console.log('Message from server:', event.data);
});
open
: Fired when the connection is establishedmessage
: Fired when data is receivederror
: Fired when an error occursclose
: Fired when the connection is closedsocket.addEventListener('open', (event) => {
console.log('WebSocket connection opened');
});
socket.addEventListener('message', (event) => {
console.log('Received message:', event.data);
});
socket.addEventListener('error', (event) => {
console.error('WebSocket error:', event);
});
socket.addEventListener('close', (event) => {
console.log('WebSocket connection closed');
});
send()
: Sends data through the WebSocket connectionclose()
: Closes the WebSocket connection// Sending data
socket.send('Hello, server!');
// Closing the connection
socket.close();
The readyState
property indicates the state of the WebSocket connection:
WebSocket.CONNECTING
(0): The connection is not yet openWebSocket.OPEN
(1): The connection is open and ready to communicateWebSocket.CLOSING
(2): The connection is in the process of closingWebSocket.CLOSED
(3): The connection is closed or couldn't be openedif (socket.readyState === WebSocket.OPEN) {
socket.send('Data');
}
socket.addEventListener('error', (error) => {
console.error('WebSocket Error:', error);
});
// Handling specific errors
socket.addEventListener('close', (event) => {
if (event.code === 1006) {
console.error('Connection closed abnormally');
}
});
const socket = new WebSocket('wss://secure.example.com');
Example heartbeat implementation:
// Client-side
function heartbeat() {
if (socket.readyState === WebSocket.OPEN) {
socket.send('__ping__');
setTimeout(heartbeat, 30000);
}
}
socket.addEventListener('open', heartbeat);
socket.addEventListener('message', (event) => {
if (event.data === '__pong__') {
console.log('Received pong');
} else {
console.log('Received:', event.data);
}
});
// Server-side
wss.on('connection', (ws) => {
ws.isAlive = true;
ws.on('pong', () => {
ws.isAlive = true;
});
ws.on('message', (message) => {
if (message === '__ping__') {
ws.send('__pong__');
}
});
});
setInterval(() => {
wss.clients.forEach((ws) => {
if (!ws.isAlive) return ws.terminate();
ws.isAlive = false;
ws.ping();
});
}, 30000);
2024 © All rights reserved - buraxta.com