WebSocket Basics for Web Developers

matt
Matthew Gros · Oct 16, 2025

TLDR

WebSockets for real-time bidirectional communication. Use for chat, notifications, live updates. SSE for server-only push.

WebSocket Basics for Web Developers

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

About the Author

matt

I build and ship automation-driven products using Laravel and modern frontend stacks (Vue/React), with a focus on scalability, measurable outcomes, and tight user experience. I’m based in Toronto, have 13+ years in PHP, and I also hold a pilot’s license. I enjoy working on new tech projects and generally exploring new technology.