A cooperative event loop for HolyPHP: timers, socket watchers,
line-oriented TCP servers, and HTTP — all in one loop, no threads needed.
Pure HolyPHP on top of the runtime's non-blocking socket primitives.
import "async";
$loop = new Loop();
$loop->after(1000, function() { echo "one second passed"; });
$loop->every(250, function() { echo "tick"; });
$loop->run(); // blocks until stop() or nothing left to wait on
import "async";
$loop = new Loop();
$loop->after(1000, function() { echo "one second passed"; });
$loop->every(250, function() { echo "tick"; });
$loop->run(); // blocks until stop() or nothing left to wait on
Method
Returns
What it does
after(int $ms, $fn)
int
one-shot timer; returns an id for cancelTimer
every(int $ms, $fn)
int
repeating timer (self-reschedules)
cancelTimer(int $id)
void
cancel a pending timer
stop()
void
leave run() from inside a callback
tick(int $maxWaitMs = 25)
bool
run one poll iteration yourself
run()
void
loop until stop() or idle
TCP: servers, watchers, lines
import "async";
// one-shot TCP server: accept callback per connection
$loop = new Loop();
$loop->listen("tcp://127.0.0.1:8080", function($client, $peer) {
stream_send($client, "hello $peer\n");
stream_close($client);
});
// raw readable-socket watcher
$loop->watch($sock, function($sock, $chunk, $eof) {
if ($eof) { return; }
echo "got: $chunk";
});
// line-oriented server with automatic ACK replies
$lp = async_line_server("tcp://0.0.0.0:9000", function($client, $line) {
return "ACK:" . strtoupper($line); // non-null return = reply line
});
$lp->run();
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.
01Timers: a launch countdown
The smallest useful event loop. every() schedules a repeating timer, after() a one-shot one, and cancelTimer() stops a repeating timer by the id it returned. When no timers or sockets are left, run() returns on its own - no explicit exit needed.
01-timers.hphp
<?php
import "async";
$loop = new Loop();
$remaining = 5;
// A repeating timer: count down once per second.
$countdownId = $loop->every(1000, function() use (&$remaining) {
echo "T-minus $remaining";
$remaining = $remaining - 1;
});
// A one-shot timer that fires in between the countdown steps.
$loop->after(2500, function() {
echo " (all systems go)";
});
// A one-shot timer: after 5.5 seconds, cancel the repeating timer.
$loop->after(5500, function() use ($loop, $countdownId) {
$loop->cancelTimer($countdownId);
echo "Liftoff!";
});
// Runs until every timer is gone, then returns.
$started = now_ms();
$loop->run();
$elapsed = now_ms() - $started;
echo "loop finished after $elapsed ms";
Try it
hphp run 01-timers.hphp
02TCP echo server
A classic echo server: every byte a client sends comes straight back. listen() accepts connections without blocking, and watch() calls a handler with ($socket, $chunk, $eof) whenever a client has data. Many clients are served at once by a single thread.
02-echo-server.hphp
<?php
import "async";
$address = "tcp://127.0.0.1:7000";
$loop = new Loop();
$connections = 0;
// Called once for every new client connection.
$loop->listen($address, function($client, $peer) use ($loop, &$connections) {
$connections = $connections + 1;
echo "[$peer] connected ($connections so far)";
stream_send($client, "Welcome! Everything you type is echoed back.\r\n");
// Called whenever this client has sent something (or hung up).
$loop->watch($client, function($socket, $chunk, $eof) use ($peer) {
if ($eof) {
echo "[$peer] disconnected";
return;
}
stream_send($socket, $chunk);
});
});
// Print a heartbeat so you can see the loop never blocks.
$loop->every(10000, function() use (&$connections) {
echo "still serving - $connections connection(s) total";
});
echo "echo server listening on $address";
$loop->run();
Try it
hphp run 02-echo-server.hphp
telnet 127.0.0.1 7000 (or: nc 127.0.0.1 7000)
03Line-based chat server
A tiny multi-user chat room over plain TCP. Each connection gets a LineReader, which turns the raw chunks from watch() into complete lines. Every line is broadcast to the other users; /nick NAME renames you and /who lists everyone in the room.
03-chat-server.hphp
<?php
import "async";
$loop = new Loop();
$sockets = []; // client id => socket handle
$names = []; // client id => nickname
// Send one line to everyone except the client with id $skip.
function broadcast(array $sockets, int $skip, string $text) {
foreach ($sockets as $id => $socket) {
if ($id != $skip) {
stream_send($socket, $text . "\r\n");
}
}
}
$loop->listen("tcp://127.0.0.1:7001", function($client, $peer) use ($loop, &$sockets, &$names) {
// Register the newcomer under a default nickname.
$id = intval($client);
$sockets[$id] = $client;
$names[$id] = "guest$id";
stream_send($client, "Welcome, guest$id! Commands: /nick NAME, /who\r\n");
broadcast($sockets, $id, "* guest$id joined from $peer");
// Turn incoming bytes into whole lines and handle each one.
$reader = new LineReader(function($line) use ($id, $client, &$sockets, &$names) {
$text = trim($line);
if ($text == "") {
return;
}
if (str_starts_with($text, "/nick ")) {
$old = $names[$id];
$names[$id] = trim(substr($text, 6));
broadcast($sockets, 0, "* $old is now known as " . $names[$id]);
} elseif ($text == "/who") {
stream_send($client, "In the room: " . implode(", ", $names) . "\r\n");
} else {
broadcast($sockets, $id, "<" . $names[$id] . "> " . $text);
}
});
// Feed the reader; on hang-up, forget the client and tell the room.
$loop->watch($client, function($socket, $chunk, $eof) use ($id, $reader, &$sockets, &$names) {
if ($eof) {
$name = $names[$id];
unset($sockets[$id]);
unset($names[$id]);
broadcast($sockets, 0, "* $name left");
return;
}
$reader->feed($chunk);
});
});
echo "chat server on 127.0.0.1:7001";
$loop->run();
Try it
hphp run 03-chat-server.hphp
nc 127.0.0.1 7001 (open two or three terminals)
04Fetching a URL without blocking
httpGet() runs an HTTP/1.1 GET on the loop itself, so timers keep firing while the response streams in - here a progress timer prints how long we have been waiting. The callback receives the raw response (status line, headers and body), which we split up and summarise.
httpGet() speaks plain http:// only and gives up after 10 seconds.
04-fetch-url.hphp
<?php
import "async";
$url = "http://example.com/";
$loop = new Loop();
$started = now_ms();
// Show that the loop stays responsive while the request is in flight.
$waitTimer = $loop->every(100, function() use ($started) {
$waited = now_ms() - $started;
echo "waiting... $waited ms";
});
// Success: split the raw response into head and body and report on both.
$onDone = function($response) use ($loop, $waitTimer, $started) {
$loop->cancelTimer($waitTimer);
$split = strpos($response, "\r\n\r\n");
if ($split === false) {
echo "malformed response";
return;
}
$head = substr($response, 0, $split);
$body = substr($response, $split + 4);
$headerLines = explode("\r\n", $head);
echo "status: " . $headerLines[0];
foreach ($headerLines as $line) {
if (str_starts_with(strtolower($line), "content-type:")) {
echo "type: " . trim(substr($line, 13));
}
}
echo "body: " . strlen($body) . " bytes";
// Pull the <title> out of the page, if it has one.
$match = [];
if (preg_match("/<title>(.*?)<\/title>/is", $body, $match) === 1) {
echo "title: " . trim($match[1]);
}
echo "took: " . (now_ms() - $started) . " ms";
};
// Failure: connection refused, DNS trouble or the 10 s timeout.
$onError = function($reason) use ($loop, $waitTimer) {
$loop->cancelTimer($waitTimer);
echo "request failed: $reason";
};
echo "GET $url";
$loop->httpGet($url, $onDone, $onError);
$loop->run();
Try it
hphp run 04-fetch-url.hphp
05A key-value store server in one function call
async_line_server() wires up listen(), watch() and a LineReader for you: your handler gets each complete line and whatever it returns is sent back as the reply. This one implements a small Redis-like protocol with SET, GET, DEL, KEYS and QUIT, plus a timer that reports stats.
05-kv-store.hphp
<?php
import "async";
$store = [];
$commandCount = 0;
// Handle one protocol line; the returned string is the reply.
$handleLine = function($client, $line, $loop) use (&$store, &$commandCount) {
$commandCount = $commandCount + 1;
$parts = explode(" ", trim($line));
$command = strtoupper($parts[0]);
if ($command == "SET" && count($parts) >= 3) {
$value = implode(" ", array_slice($parts, 2));
$store[$parts[1]] = $value;
return "OK";
}
if ($command == "GET" && count($parts) == 2) {
if (array_key_exists($parts[1], $store)) {
return $store[$parts[1]];
}
return "(nil)";
}
if ($command == "DEL" && count($parts) == 2) {
unset($store[$parts[1]]);
return "OK";
}
if ($command == "KEYS") {
return implode(" ", array_keys($store));
}
if ($command == "QUIT") {
$server = $loop as Loop;
$server->unwatch($client);
stream_close($client);
return null;
}
return "ERR unknown command: $line";
};
// Greet every new connection.
$onConnect = function($client, $peer) {
echo "client connected: $peer";
stream_send($client, "kv-store ready\r\n");
};
$loop = async_line_server("tcp://127.0.0.1:7002", $handleLine, $onConnect);
// The returned Loop is an ordinary loop: add a stats timer to it.
$loop->every(30000, function() use (&$store, &$commandCount) {
echo "stats: " . count($store) . " keys, $commandCount commands served";
});
echo "kv-store listening on 127.0.0.1:7002";
$loop->run();
Try it
hphp run 05-kv-store.hphp
nc 127.0.0.1 7002 then type: SET color blue / GET color / KEYS