A single-file RFC 6455 WebSocket server, written in HolyPHP itself.
Real SHA-1 handshake, text/binary frames, fragmentation, ping/pong, close handshake,
and non-blocking I/O so one slow client never blocks the others.
stdlib — embeddedRFC 6455browser-compatiblenon-blocking sockets~450 lines of HolyPHP
This adds the library to hphp.yaml, installs it into .hphp/packages/websocket/ and pins the exact version in hphp.lock:
require:
websocket: "^1.0"
Use it
import "websocket";
websocket is bundled with the compiler, so import "websocket"; also works in a single file without installing anything, and hphp install works offline.
Outside a project
hphp install websocket # for your user, shared by all scripts
hphp create myapp # or start a project, then: hphp install websocket
5 complete programs. Every one is type-checked with the compiler before the site is published; copy one into src/ of a project (hphp create) and run it.
01WebSocket echo server
The "hello world" of WebSockets: every text message a browser sends is sent straight back. WebSocketServer does the HTTP upgrade handshake and the framing; you only assign closures to onOpen, onMessage and onClose, and call run().
To test it, open a browser console and run ws = new WebSocket("ws://127.0.0.1:9001"), then ws.send("hello"); ws.onmessage = (e) => console.log(e.data) prints the replies.
01-echo-server.hphp
<?php
import "websocket";
$server = new WebSocketServer("tcp://127.0.0.1:9001");
// A browser finished the handshake.
$server->onOpen = function(int $client) use ($server): void {
echo "client $client connected from " . $server->peerOf($client);
$server->send($client, "welcome, you are client $client");
};
// A text message arrived: send it back, upper-cased so you can tell.
$server->onMessage = function(int $client, string $message) use ($server): void {
echo "client $client says: $message";
$server->send($client, "echo: " . strtoupper($message));
};
// The browser tab closed or navigated away.
$server->onClose = function(int $client, int $code): void {
echo "client $client left (close code $code)";
};
echo "echo server on ws://127.0.0.1:9001";
$server->run();
Try it
hphp run 01-echo-server.hphp
02Chat room with nicknames
A complete chat backend. broadcast() sends a message to every open client, and its second argument skips one client - handy for "everyone but the sender". Users pick a name with /nick NAME, list the room with /who, and everyone hears about joins and departures.
02-chat-room.hphp
<?php
import "websocket";
$server = new WebSocketServer("tcp://127.0.0.1:9002");
$names = []; // client id => nickname
// Someone joined: give them a default name and tell the others.
$server->onOpen = function(int $client) use ($server, &$names): void {
$names[$client] = "guest$client";
$server->send($client, "Welcome! Type /nick NAME to choose a name, /who to list users.");
$server->broadcast("* guest$client joined", $client);
};
// A message: either a command or a line of chat.
$server->onMessage = function(int $client, string $message) use ($server, &$names): void {
$text = trim($message);
if ($text == "") {
return;
}
if (str_starts_with($text, "/nick ")) {
$old = $names[$client];
$names[$client] = trim(substr($text, 6));
$server->broadcast("* $old is now " . $names[$client]);
return;
}
if ($text == "/who") {
$count = $server->clientCount();
$server->send($client, "$count online: " . implode(", ", $names));
return;
}
// Plain chat: everyone else sees it with the sender's name.
$server->broadcast($names[$client] . ": " . $text, $client);
};
// Someone left: forget their name and tell the room. (A connection
// that never finished the handshake has no name and is skipped.)
$server->onClose = function(int $client, int $code) use ($server, &$names): void {
if (!array_key_exists($client, $names)) {
return;
}
$name = $names[$client];
unset($names[$client]);
$server->broadcast("* $name left");
};
if (!$server->listen()) {
echo "could not listen on port 9002";
exit(1);
}
echo "chat room on ws://127.0.0.1:9002";
$server->run();
Try it
hphp run 02-chat-room.hphp
03Pushing live updates from your own loop
Servers do not have to wait for clients to speak. Instead of the blocking run(), this program drives the server with tick() from its own loop, and once a second pushes a fake stock price to every open client. Every ten seconds it also ping()s each client so dead connections are noticed, and prints clientCount().
03-live-ticker.hphp
<?php
import "websocket";
$server = new WebSocketServer("tcp://127.0.0.1:9003");
if (!$server->listen()) {
echo "could not listen on port 9003";
exit(1);
}
$server->onOpen = function(int $client) use ($server): void {
$server->send($client, "subscribed to HPHP quotes");
};
$price = 100.0;
$lastQuote = 0;
$lastPing = 0;
echo "ticker on ws://127.0.0.1:9003";
while (true) {
// Accept new clients and read incoming frames (waits at most 50 ms).
$server->tick(50);
$now = time();
// Once a second: move the price a little and push it to everyone.
if ($now != $lastQuote) {
$lastQuote = $now;
$price = $price + (rand(-100, 100) / 100);
$quote = "HPHP " . number_format($price, 2) . " at " . date("H:i:s");
$server->broadcast($quote);
}
// Every ten seconds: ping each client and report the audience.
if ($now - $lastPing >= 10) {
$lastPing = $now;
foreach ($server->clients() as $client) {
$server->ping($client);
}
echo "listeners: " . $server->clientCount();
}
}
Try it
hphp run 03-live-ticker.hphp
04A live poll with JSON messages
Real apps rarely send bare strings: here every message is JSON. A client votes with {"vote": "tabs"}, may change its mind, and every connected client receives the new tally as {"type": "tally", ...} the moment it changes. Bad input gets an {"type": "error"} reply only to the sender.
04-live-poll.hphp
<?php
import "websocket";
$options = ["tabs", "spaces", "both"];
$votes = []; // client id => chosen option
// Count the votes per option and build the message everyone receives.
function tally_message(array $options, array $votes): string {
$counts = [];
foreach ($options as $option) {
$counts[$option] = 0;
}
foreach ($votes as $choice) {
$counts[$choice] = $counts[$choice] + 1;
}
return json_encode(["type" => "tally", "counts" => $counts, "voters" => count($votes)]);
}
$server = new WebSocketServer("tcp://127.0.0.1:9004");
// New client: show the question and the current standings.
$server->onOpen = function(int $client) use ($server, $options, &$votes): void {
$question = ["type" => "question", "text" => "Tabs or spaces?", "options" => $options];
$server->send($client, json_encode($question));
$server->send($client, tally_message($options, $votes));
};
// A vote: validate it, record it, broadcast the new tally.
$server->onMessage = function(int $client, string $message) use ($server, $options, &$votes): void {
$data = json_decode($message);
if (!is_array($data) || !array_key_exists("vote", $data)) {
$server->send($client, json_encode(["type" => "error", "text" => "send {\"vote\": \"...\"}"]));
return;
}
$choice = $data["vote"];
if (!in_array($choice, $options)) {
$server->send($client, json_encode(["type" => "error", "text" => "unknown option"]));
return;
}
$votes[$client] = $choice;
$server->broadcast(tally_message($options, $votes));
};
// A voter left: their vote leaves with them.
$server->onClose = function(int $client, int $code) use ($server, $options, &$votes): void {
unset($votes[$client]);
$server->broadcast(tally_message($options, $votes));
};
echo "poll running on ws://127.0.0.1:9004";
$server->run();
Try it
hphp run 04-live-poll.hphp
05Under the hood: handshake and frames
The server is built from small exported functions you can use on their own - for tests, a custom server, or just to learn the protocol. This program needs no network: it checks the handshake against the example in RFC 6455, encodes a frame with ws_frame(), and decodes a masked client frame with ws_decode(), including a frame that is not complete yet.
05-wire-format.hphp
<?php
import "websocket";
// 1. The handshake: pull the key out of a request, compute the answer.
$request = "GET /chat HTTP/1.1\r\n"
. "Host: server.example.com\r\n"
. "Upgrade: websocket\r\n"
. "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
. "\r\n";
$key = ws_request_key($request);
echo "client key: $key";
echo "accept key: " . ws_accept_key($key);
echo "RFC expects: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=";
// 2. A server frame: FIN + text opcode, length, then the payload.
$frame = ws_frame("Hello");
echo "server frame: " . bin2hex($frame);
// 3. A client frame (from RFC 6455 section 5.7): masked "Hello".
$clientFrame = hex2bin("818537fa213d7f9f4d5158");
$decoded = ws_decode($clientFrame);
echo "decoded: opcode " . $decoded["opcode"]
. ", payload '" . $decoded["payload"] . "'"
. ", " . $decoded["consumed"] . " bytes used";
// 4. Only half a frame has arrived: ws_decode asks for more bytes.
$half = substr($clientFrame, 0, 6);
if (ws_decode($half) == null) {
echo "half a frame: incomplete, wait for more data";
}
// 5. Close frames carry a 2-byte status code (1000 = normal closure).
$close = ws_frame(ws_close_payload(1000), 8);
echo "close frame: " . bin2hex($close);