WebSocket Nedir? Gerçek Zamanlı İletişim Rehberi
Chat uygulamanız sayfayı yenilemeden mesaj gösterebiliyor mu? Dashboard'unuz canlı veri akıtabiliyor mu? WebSocket ile sunucu ve istemci arasında sürekli, çift yönlü iletişim kurun.
WebSocket Tanımı
WebSocket, istemci ve sunucu arasında kalıcı, çift yönlü (full-duplex) iletişim kanalı sağlayan bir protokoldür. HTTP'nin aksine, bağlantı bir kez kurulduktan sonra her iki taraf da istediği zaman veri gönderebilir.
HTTP vs WebSocket
HTTP (Polling):
Client ──"Yeni mesaj var mı?"──→ Server (her 3 saniye)
Client ←──"Hayır"──────────── Server
Client ──"Yeni mesaj var mı?"──→ Server
Client ←──"Evet! İşte mesaj"── Server
WebSocket:
Client ←→ Server (sürekli açık bağlantı)
Server ──"Yeni mesaj geldi!"──→ Client (anında)
| Özellik | HTTP Polling | WebSocket | |---------|-------------|-----------| | Bağlantı | Her istekte yeni | Kalıcı | | Yön | İstemci → Sunucu | Çift yönlü | | Gecikme | Yüksek (polling aralığı) | Çok düşük | | Overhead | Yüksek (HTTP headers) | Düşük (frame header) | | Kaynak kullanımı | Yüksek | Düşük |
WebSocket Nasıl Çalışır?
1. Handshake (HTTP Upgrade)
Client: GET /chat HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Server: HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
2. Veri İletişimi
Bağlantı kurulduktan sonra her iki taraf da frame göndererek iletişim kurar.
3. Kapatma
Her iki taraf bağlantıyı kapatabilir.
Vanilla WebSocket API
Sunucu (Node.js)
const { WebSocketServer } = require('ws');
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', (ws) => {
console.log('Yeni bağlantı');
ws.on('message', (data) => {
const message = JSON.parse(data);
// Tüm bağlı istemcilere yayınla
wss.clients.forEach((client) => {
if (client.readyState === 1) {
client.send(JSON.stringify({
user: message.user,
text: message.text,
time: new Date().toISOString()
}));
}
});
});
ws.on('close', () => console.log('Bağlantı kapandı'));
});
İstemci (Browser)
const ws = new WebSocket('ws://localhost:8080');
ws.onopen = () => {
console.log('Bağlantı kuruldu');
ws.send(JSON.stringify({ user: 'Ali', text: 'Merhaba!' }));
};
ws.onmessage = (event) => {
const message = JSON.parse(event.data);
console.log(`${message.user}: ${message.text}`);
};
ws.onclose = () => console.log('Bağlantı kapandı');
ws.onerror = (err) => console.error('Hata:', err);
Socket.IO ile Daha Kolay
Socket.IO, WebSocket üzerine kurulu bir kütüphanedir. Otomatik reconnection, room desteği ve fallback mekanizması sunar.
Sunucu
const { Server } = require('socket.io');
const io = new Server(3000, { cors: { origin: '*' } });
io.on('connection', (socket) => {
console.log('Kullanıcı bağlandı:', socket.id);
// Room'a katıl
socket.on('join-room', (room) => {
socket.join(room);
});
// Mesaj gönder
socket.on('chat-message', (data) => {
io.to(data.room).emit('new-message', {
user: data.user,
text: data.text,
time: new Date()
});
});
// Typing indicator
socket.on('typing', (data) => {
socket.to(data.room).emit('user-typing', data.user);
});
socket.on('disconnect', () => {
console.log('Kullanıcı ayrıldı:', socket.id);
});
});
İstemci
import { io } from 'socket.io-client';
const socket = io('http://localhost:3000');
socket.emit('join-room', 'genel');
socket.on('new-message', (msg) => {
addMessageToUI(msg);
});
function sendMessage(text) {
socket.emit('chat-message', {
room: 'genel',
user: 'Ali',
text
});
}
Yaygın Kullanım Alanları
| Kullanım | Örnek | |----------|-------| | Chat | WhatsApp Web, Slack | | Canlı bildirimler | GitHub, Twitter | | Canlı veri | Borsa, kripto fiyatları | | Oyun | Multiplayer oyunlar | | Collaborative editing | Google Docs | | IoT | Sensör verileri |
WebSocket vs Alternatifler
| Teknoloji | Yön | Kullanım | |-----------|-----|----------| | WebSocket | Çift yönlü | Chat, oyun | | SSE | Sunucu → İstemci | Bildirimler, feed | | HTTP Polling | İstemci → Sunucu | Basit güncellemeler | | Long Polling | İstemci → Sunucu | SSE alternatifi |
Best Practices
- Heartbeat/ping mekanizması — Ölü bağlantıları tespit edin
- Reconnection stratejisi — Exponential backoff ile yeniden bağlanın
- Authentication — Bağlantı kurarken token doğrulama
- Rate limiting — Mesaj flood'unu engelleyin
- Compression — Büyük mesajlar için sıkıştırma kullanın
- Horizontal scaling — Redis Pub/Sub ile çoklu sunucu desteği
Sonuç
WebSocket, gerçek zamanlı uygulamaların temel yapı taşıdır. Chat, bildirimler, canlı veri ve multiplayer oyunlar için idealdir. Basit projeler için vanilla WebSocket API yeterlidir; karmaşık senaryolar için Socket.IO güçlü bir çözüm sunar.
WebSocket ve gerçek zamanlı uygulamaları LabLudus platformunda pratik yaparak öğrenin.