Long-Polling, WebSockets, SSE and Comet: Complete Breakdown with PHP Code

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Still refreshing the page manually? Time to go real-time

\n\n

Imagine: you open an online exchange, and the dollar rate is frozen solid. You hit F5, hit it again — and it doesn't change. Sound familiar? Now imagine the rate updates itself, like in a movie — smoothly and without delays. This isn't magic, it's real-time technologies. They are what turn a static website into a living organism: chats, notifications, dashboards that update in real time.

\n\n

Today we'll break down the four pillars of the real-time web: Long-Polling, WebSockets, Server-Sent Events (SSE) and Comet. I'll show you how they work "under the hood" and provide ready-to-use PHP code you can implement right now. Let's go!

\n\n

This article is written for the educational portal pythonlib.ru — where we turn complex concepts into understandable tools.

\n\n

The gist: what's behind the terms?

\n\n

When you open a regular page, the browser makes a request, the server responds — and the connection is closed. Simple. But what if the server wants to "knock" on your door with new data on its own? That's where the real fun begins.

\n\n
    \n
  • Long-Polling — the old but reliable grandfather. The client "hangs" on the server and waits for it to deign to respond.
  • \n
  • WebSockets — the trend of recent years. A full-fledged two-way channel, like a telephone line.
  • \n
  • Server-Sent Events (SSE) — one-way broadcast from server to client. Ideal for news feeds and stock quotes.
  • \n
  • Comet — a general term for techniques where the server "pushes" data to the client without an additional request. Long-Polling and SSE are specific cases of Comet.
  • \n
\n\n

Technology #1: Long-Polling — the grandfather of real-time

\n\n

Long-Polling is when the client tells the server: "I'll wait as long as it takes, just respond when data appears." The client opens a connection and keeps it open until the server sends a response. After receiving the response, the client immediately creates a new request. It's an endless chain.

\n\n

Pros: works on any hosting, requires no additional libraries, supported by all browsers.

\n

Cons: lots of extra headers, server load, delays with a large number of clients.

\n\n

PHP Example (Long-Polling)

\n\n
<?php\n// long_polling.php\nheader('Content-Type: text/plain; charset=utf-8');\nheader('Cache-Control: no-cache');\n\n$timeout = 30; // wait max 30 seconds\n$start = time();\n\n// Simulate new data appearing\n$data = getNewDataFromDB(); // your data retrieval function\n\nwhile (empty($data)) {\n    if ((time() - $start) > $timeout) {\n        echo json_encode(['status' => 'timeout', 'data' => null]);\n        flush();\n        exit;\n    }\n    usleep(500000); // sleep 0.5 seconds\n    $data = getNewDataFromDB();\n}\n\necho json_encode(['status' => 'ok', 'data' => $data]);\nflush();\n?>
\n\n

On the client side (JavaScript) it will look like this:

\n\n
function longPoll() {\n    fetch('/long_polling.php')\n        .then(response => response.json())\n        .then(data => {\n            if (data.status === 'ok') {\n                console.log('New data:', data.data);\n                // update the interface\n            }\n            longPoll(); // immediately create a new request\n        })\n        .catch(error => {\n            console.error('Error:', error);\n            setTimeout(longPoll, 1000); // reconnect after one second\n        });\n}\nlongPoll();
\n\n

See? The client hangs, waits, receives data — and hangs again. This is Long-Polling in PHP in its pure form.

\n\n

Technology #2: WebSockets — a two-way highway

\n\n

WebSockets

Blogs

Book Recommendations