websocket

WebSocket servers: handshake, frames, chat-style broadcasting.

v1.0.0Web & networkingbundledimport "websocket";
Overview Installation Documentation Examples

Overview

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 — embedded RFC 6455 browser-compatible non-blocking sockets ~450 lines of HolyPHP

Minimal server

import "websocket";

$server = new WebSocketServer("tcp://0.0.0.0:9001");

$server->onMessage = function(int $client, string $msg): void {
    $server->broadcast($msg);        // chat-style echo
};

$server->run();                      // blocking event loop

Connect from any browser:

const ws = new WebSocket("ws://localhost:9001");
ws.onmessage = (e) => console.log(e.data);
ws.send("hello");

Installation

In a project

Inside a project (a folder with hphp.yaml, see Projects & packages):

hphp install websocket

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
Packagewebsocket
Version1.0.0 (follows the compiler)
Entry filewebsocket.hphp
Sourcepackages/lib/websocket ↗

Documentation

Minimal server

import "websocket";

$server = new WebSocketServer("tcp://0.0.0.0:9001");

$server->onMessage = function(int $client, string $msg): void {
    $server->broadcast($msg);        // chat-style echo
};

$server->run();                      // blocking event loop

Connect from any browser:

const ws = new WebSocket("ws://localhost:9001");
ws.onmessage = (e) => console.log(e.data);
ws.send("hello");

Construction

new WebSocketServer(string $addr = "tcp://127.0.0.1:9001")
PropertyTypeMeaning
$addrstringbind address, tcp://host:port
$verboseboollog lifecycle + frames to stdout
$onOpenclosurefn(int $client)
$onMessageclosurefn(int $client, string $message) — text frames
$onBinaryclosurefn(int $client, string $bytes) — binary frames
$onCloseclosurefn(int $client, int $code)

Client ids are small integers starting at 1, stable for the connection's lifetime.

Methods

bool listen() // bind + listen; false on failure void run() // blocking loop until stop() void stop() // leave the loop from a callback bool isRunning() bool tick(int $timeoutMs = 50) // one pass: accept + read bool send(int $client, string $message) // text frame bool sendBinary(int $client, string $bytes) // binary frame bool ping(int $client) int broadcast(string $message, int $except = 0) // to all (minus one) void close(int $client, int $code = 1000) // clean close handshake void drop(int $client, int $code = 1000) // force disconnect int clientCount() bool isOpen(int $client) string peerOf(int $client) // "ip:port" array clients() // ids of open clients

Integrate into your own loop

Don't want the blocking run()? Call tick() from your own loop — it accepts pending connections and drains readable sockets, then returns.

while ($server->tick(10)) {          // your game/render loop here
    do_frame();
}

Protocol details handled for you

FeatureStatus
HTTP upgrade handshake (Sec-WebSocket-Accept, real SHA-1 + base64)✓
Masked client frames (unmasked in server direction)✓
Fragmented messages (continuation frames, opcode 0)✓
Text (1) / binary (2) opcodes✓
Ping/pong keepalive (opcodes 9/10)✓
Close handshake with status codes (opcode 8)✓
64-bit extended payload lengths✓
One slow client never blocks others (poll-based)✓

Lower-level pieces (exported)

The library also exposes its frame codec if you want to build something exotic:

string ws_frame(string $payload, int $opcode = 1) array? ws_decode(string $buf) // null while frame incomplete string ws_accept_key(string $key) // Sec-WebSocket-Accept string ws_close_payload(int $code)

ws_decode returns ["fin" => bool, "opcode" => int, "payload" => string, "consumed" => int].

Examples

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);
Try it
hphp run 05-wire-format.hphp