Real-Time Without Polling
WebSockets keep a connection open for instant updates.
When to Use WebSockets
- Chat applications
- Live notifications
- Collaborative editing
- Gaming
- Live dashboards
Basic Example
// Client
const ws = new WebSocket('wss://example.com/socket');
ws.onopen = () => {
console.log('Connected');
ws.send(JSON.stringify({ type: 'subscribe', channel: 'updates' }));
};
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log('Received:', data);
};
ws.onclose = () => {
console.log('Disconnected');
// Implement reconnection logic
};
Laravel Broadcasting
// Install
composer require pusher/pusher-php-server
// Event
class OrderShipped implements ShouldBroadcast
{
public function broadcastOn()
{
return new PrivateChannel('orders.'.$this->order->user_id);
}
}
// Trigger
event(new OrderShipped($order));
// Laravel Echo client
Echo.private(`orders.${userId}`)
.listen('OrderShipped', (e) => {
console.log('Order shipped:', e.order);
});
Server-Sent Events (SSE)
One-way server to client (simpler):
// Server
return response()->stream(function () {
while (true) {
echo "data: " . json_encode(['time' => now()]) . "\n\n";
ob_flush();
flush();
sleep(1);
}
}, 200, ['Content-Type' => 'text/event-stream']);
// Client
const source = new EventSource('/stream');
source.onmessage = (e) => console.log(JSON.parse(e.data));
Choose Wisely
- WebSocket: Bidirectional, low latency
- SSE: Server push only, simpler
- Polling: When real-time isn't critical
