← Blog'a Dön
TECHNICAL

What Is WebSocket? Real-Time Communication Explained

F. Çağrı Bilgehan6 Şubat 202610 dk okuma
websocketreal-timesocket.ioweb development

What Is WebSocket? Real-Time Communication Guide

Can your chat app show messages without refreshing? Can your dashboard stream live data? WebSocket creates a persistent, bidirectional channel between client and server.

What Is WebSocket?

WebSocket is a protocol that provides a persistent, full-duplex communication channel between client and server. Unlike HTTP, once connected, both sides can send data at any time.

HTTP vs WebSocket

HTTP (Polling):
Client ──"New messages?"──→ Server (every 3 seconds)
Client ←──"No"──────────── Server
Client ──"New messages?"──→ Server
Client ←──"Yes! Here it is"── Server

WebSocket:
Client ←→ Server (persistent connection)
Server ──"New message!"──→ Client (instant)

| Feature | HTTP Polling | WebSocket | |---------|-------------|-----------| | Connection | New each request | Persistent | | Direction | Client → Server | Bidirectional | | Latency | High (poll interval) | Very low | | Overhead | High (HTTP headers) | Low (frame header) |

How WebSocket Works

1. Handshake (HTTP Upgrade)

Client: GET /chat HTTP/1.1
        Upgrade: websocket

Server: HTTP/1.1 101 Switching Protocols
        Upgrade: websocket

2. Data Exchange

Both sides send data frames once connected.

Vanilla WebSocket

Server (Node.js)

const { WebSocketServer } = require('ws');
const wss = new WebSocketServer({ port: 8080 });

wss.on('connection', (ws) => {
  ws.on('message', (data) => {
    const msg = JSON.parse(data);
    wss.clients.forEach((client) => {
      if (client.readyState === 1) {
        client.send(JSON.stringify({
          user: msg.user,
          text: msg.text,
          time: new Date().toISOString()
        }));
      }
    });
  });
});

Client (Browser)

const ws = new WebSocket('ws://localhost:8080');

ws.onopen = () => {
  ws.send(JSON.stringify({ user: 'Ali', text: 'Hello!' }));
};

ws.onmessage = (event) => {
  const msg = JSON.parse(event.data);
  console.log(`${msg.user}: ${msg.text}`);
};

Socket.IO

Socket.IO adds auto-reconnection, rooms, and fallback mechanisms on top of WebSocket.

Server

const { Server } = require('socket.io');
const io = new Server(3000);

io.on('connection', (socket) => {
  socket.on('join-room', (room) => socket.join(room));

  socket.on('chat-message', (data) => {
    io.to(data.room).emit('new-message', {
      user: data.user,
      text: data.text,
      time: new Date()
    });
  });
});

Client

import { io } from 'socket.io-client';
const socket = io('http://localhost:3000');

socket.emit('join-room', 'general');
socket.on('new-message', (msg) => addMessageToUI(msg));

Common Use Cases

| Use Case | Example | |----------|---------| | Chat | WhatsApp Web, Slack | | Notifications | GitHub, Twitter | | Live data | Stock prices, crypto | | Gaming | Multiplayer games | | Collaboration | Google Docs | | IoT | Sensor data streams |

WebSocket vs Alternatives

| Tech | Direction | Best For | |------|-----------|----------| | WebSocket | Bidirectional | Chat, gaming | | SSE | Server → Client | Notifications, feeds | | HTTP Polling | Client → Server | Simple updates |

Best Practices

  1. Heartbeat/ping — Detect dead connections
  2. Reconnection — Exponential backoff strategy
  3. Authentication — Validate tokens during handshake
  4. Rate limiting — Prevent message flooding
  5. Compression — Compress large payloads
  6. Horizontal scaling — Use Redis Pub/Sub for multi-server

Conclusion

WebSocket is the backbone of real-time applications. It's ideal for chat, notifications, live data, and multiplayer games. Use vanilla WebSocket for simple projects; Socket.IO for complex scenarios with rooms and reconnection.

Learn WebSocket and real-time apps on LabLudus.

İlgili Yazılar

How to Build a SaaS Product: A Starter Guide

What is SaaS, how is it built, and what steps should you follow for a successful SaaS product? Technology selection, pricing, and MVP strategy guide.

No-Code and Low-Code: Build Apps Without Coding

What are no-code and low-code platforms, what are their advantages, and when should you use them? Comparing Bubble, Webflow, Retool, and Airtable.