Skip to content

What is WebSocket

Key idea:

WebSocket (RFC 6455) — a protocol on top of TCP providing full-duplex bidirectional communication between browser and server. Unlike HTTP, the connection stays open; the server can push without a request. Use-cases: real-time chat, live notifications, multiplayer games, collaborative editing. Handshake via HTTP Upgrade header → switch to ws:// or wss://.

Below: details, example, related terms, FAQ.

Check your site →

Details

  • Handshake: HTTP GET with Upgrade: websocket + Connection: Upgrade
  • Protocol: ws:// (plaintext), wss:// (TLS, mandatory in production)
  • Frames: binary or UTF-8 text. Max frame 2^63 bytes (rarely hit)
  • Heartbeat: ping/pong frames for keep-alive
  • Alternative: Server-Sent Events (SSE) for server→client only

Example

const ws = new WebSocket('wss://example.com/socket');
ws.onmessage = e => console.log(e.data);
ws.onopen = () => ws.send(JSON.stringify({ type: 'subscribe' }));

Related Terms

How WebSocket Works: Under the Hood

The WebSocket protocol operates over a TCP connection, ensuring a persistent link between the client and server. Initially, the communication begins with an HTTP request that includes an Upgrade header. This header signals the server to switch protocols from HTTP to WebSocket.

Once the server acknowledges the request, a handshake occurs, and the connection is established. The client and server can then exchange data freely in both directions without the overhead of HTTP headers. This is achieved through the use of frames, which encapsulate the messages sent over the WebSocket connection.

The WebSocket frames consist of:

  • FIN: Indicates the end of a message.
  • Opcode: Defines the type of data being sent (text, binary, close, ping, pong).
  • Payload Length: Indicates the size of the message.
  • Masking Key: Used for security to prevent cross-site attacks.

This design enables efficient real-time communication, making WebSockets ideal for applications requiring low latency and high interaction, such as stock tickers and online gaming.

WebSocket Configuration Examples

To implement WebSocket in your applications, you can use various programming languages and libraries. Below are practical examples for both a client-side and server-side implementation.

Client-Side JavaScript Example:

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

socket.onopen = function(event) {
  console.log('Connection established!');
};

socket.onmessage = function(event) {
  console.log('Message from server:', event.data);
};

socket.onerror = function(error) {
  console.error('WebSocket error:', error);
};

socket.onclose = function(event) {
  console.log('Connection closed:', event);
};

Server-Side Node.js Example:

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:', message);
  });
  ws.send('Hello! Client connected.');
});

These examples illustrate how to establish a WebSocket connection, handle messages, and manage connection events. Adjust the URLs and ports as needed for your application.

Common Issues and Troubleshooting WebSocket Connections

When working with WebSockets, developers may encounter various issues that can hinder the establishment or stability of connections. Here are some common problems and their solutions:

  • Connection Refused: This typically occurs when the WebSocket server is not running or is unreachable. Ensure that the server is active and the correct URL is being used.
  • Protocol Errors: If the handshake fails, it may be due to an incorrect Upgrade header or an unsupported WebSocket version. Confirm that the server is set up to accept WebSocket connections and that the client is using a compatible version.
  • Network Issues: Firewalls or proxies might block WebSocket traffic. Check firewall settings and ensure that ports 80 (for ws) and 443 (for wss) are open.
  • Message Size Limits: Some servers impose limits on the size of messages. If you encounter issues sending large messages, consider breaking them into smaller chunks.

For persistent connection errors, utilize tools like Chrome DevTools to inspect WebSocket frames and monitor network activity. This allows you to troubleshoot connection states and identify potential issues more effectively.

Learn more

Frequently Asked Questions

WebSocket or SSE?

WebSocket — bidirectional (both send). SSE — one-way (server→client only). SSE is simpler and works over HTTP, WebSocket is faster.

How to handle disconnects?

Implement reconnect with exponential backoff. Socket.IO does this automatically.

Scaling?

One Node.js handles 10k+ concurrent WebSockets. For 100k+ — Redis pub/sub between instances or a managed service (Ably, Pusher).

Try the live tool that powered this guide

Free plan — 10 monitors, checks every 5 min, no card required. Upgrade for 1-minute interval and multi-region monitoring.