How WebSocket Works - Understanding Real-time Bidirectional Communication

10 min read | 2025.12.13

What is WebSocket

WebSocket is a protocol that enables bidirectional real-time communication between clients and servers. It is used in applications requiring immediacy, such as chat apps, online games, and stock price displays.

WebSocket URLs: ws:// (unencrypted) and wss:// (TLS encrypted) are used.

Differences Between HTTP and WebSocket

FeatureHTTPWebSocket
Communication DirectionClient → ServerBidirectional
ConnectionConnect/disconnect per requestPersistent
Server PushNot possiblePossible
OverheadHTTP headers sent every timeOnly on initial connection
Real-time capabilityLowHigh

WebSocket Handshake

# Request from client
GET /chat HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==

# Response from server
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade

JavaScript Implementation Example

const socket = new WebSocket('wss://example.com/chat');

socket.addEventListener('open', (event) => {
    console.log('Connection successful');
    socket.send('Hello Server!');
});

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

Socket.IO

Socket.IO is a feature-rich library based on WebSocket.

  • Fallback: Uses HTTP long polling when WebSocket is unavailable
  • Auto-reconnection: Automatically reconnects on disconnection
  • Room feature: Groups clients together

Summary

WebSocket is a powerful protocol for enabling real-time bidirectional communication. Understanding the differences from HTTP and properly selecting and implementing it based on your application requirements is important.

← Back to list