Download the PHP package phasync/server without Composer
On this page you can find all versions of the php package phasync/server. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download phasync/server
More information about phasync/server
Files in phasync/server
Package server
Short Description TCP, UDP and Unix socket networking for PHP using phasync coroutines.
License MIT
Informations about the package server
phasync/net
Formerly
phasync/server, which stays available for 1.x.
TCP, UDP and Unix socket networking for PHP using phasync coroutines. MIT, no dependencies beyond phasync: the Ennerd philosophy.
The API follows Go's net package: listen() gives you a Listener that hands you
connections, dial() connects, and listenPacket() gives you a UDP PacketConn. You start
one coroutine per connection, and connections are plain PHP stream resources, so every
stream function and library works with them.
Installation
For production, also see the phasync extension and JIT.
Listening: listen()
Connections are plain non-blocking stream resources. Call phasync::readable() /
phasync::writable() before reading or writing, so the coroutine waits instead of getting
an empty read. This is also the fastest pattern for a server, with or without
the phasync extension.
foreach over the listener accepts connections until it is closed ($listener->close()
from any coroutine). To take one connection at a time, as with Go's Accept():
Either way, a connection already waiting in the kernel's queue is taken without waiting for the event loop, so a burst of new connections is admitted at once.
With ext-sockets, the listener and the connections it accepts are close-on-exec: processes your
application starts (exec(), proc_open()) don't inherit them. When accepting fails for lack of
file descriptors, accept() waits 0.1 s and retries, as long as the connection is still queued.
Several addresses
A listener listens on one address. For several, run one accept loop per address:
To handle connections from all of them in one place, have each loop write to a shared channel instead:
Read the channel from its own coroutine, as above, not from the coroutine that created it: phasync currently treats a channel's creator waiting on it for more than 100 ms as a likely deadlock and throws.
Unix domain sockets
close() removes the socket file, so the path can be bound again after a restart.
To accept from a socket that another process made listening (an application that creates the
socket, then forks workers that all accept from it), wrap it with Listener::fromStream().
Creating the socket stays with the application; close() then closes only this process's
descriptor and leaves the file alone. A Server takes the listener too: serve(Listener::fromStream($stream)).
Keepalive
Accepted TCP connections get TCP keepalive, as in Go: a first probe after 15 s idle, then every
15 s, dropped after 9 unanswered, so a peer that vanished without closing is noticed. Set the
seconds with the keepalive socket option (serve(): the keepalive option); 0 or false
turns it off. It needs ext-sockets (PHP's stream contexts don't apply keepalive to accepted
sockets) and is silently not applied without it.
Port 0
Listening on port 0 picks a free port; addr() returns the real one:
API
Serving connections: serve() and Duplex
serve() is a server that hands out connections as Duplex objects instead of stream
resources. A Duplex reads and writes, waiting in the event loop, and behaves the same however
the bytes travel: this is the API for protocol code (an HTTP server, a WebSocket).
Duplex |
|
|---|---|
read(int $max = 65536, ?float $timeout = null): string |
The next bytes, waiting for them; '' only at the end (the peer finished, or the connection closed) |
write(string $bytes, ?float $timeout = null): void |
All of $bytes; writes from several coroutines never interleave; waits while the peer is slow |
eof(): bool |
The peer finished sending and everything was read |
end(): void |
Finish our side; we can still read |
close(): void |
Close once what was written is sent; waiting reads end with '', writes throw IOException |
peer(), local() |
The two ends' addresses |
serve() options: backlog, so_reuseport (default false; several processes can share a
port when they all opt in), tcp_nodelay (default true), keepalive (seconds, default 15; 0
turns it off), max_connections (new connections wait in the kernel's backlog meanwhile;
isFull()). A slow reader pauses its client: data it hasn't read stays in the client's socket.
new StreamDuplex($stream) makes any stream resource a Duplex; dial() already returns one.
Connecting: dial()
Connect without blocking other coroutines, including the DNS lookup and a TLS handshake.
dial() returns a Duplex, the same type serve() hands out, so client and server code
share the same read/write API:
UDP: listenPacket()
A PacketConn is one UDP socket, for a server or a client (bind port 0 for a client).
Datagrams already waiting are taken before waiting again. For several addresses, run one
loop per address as with listen().
API
Dns
Async DNS resolution (used automatically by dial()):
- Non-blocking UDP queries to the system nameserver
- IPv4 (A) and IPv6 (AAAA)
- Reads
/etc/hostsfirst - Caches results using the DNS TTL
- Falls back to 8.8.8.8 if no nameserver is configured
Socket options
One flat option shape, PHP's own stream-context names, for listen(), serve(),
listenPacket() and dial() alike:
| Option | Default | Why |
|---|---|---|
backlog |
net.core.somaxconn on Linux, capped at 65535 (older kernels store it in 16 bits); 511 elsewhere |
Room for connection bursts. |
so_reuseport |
false |
Opt in to let several processes listen on the same port, for multi-process scaling and graceful restarts. Off by default so a forgotten extra process doesn't silently share a port. |
tcp_nodelay |
true |
Small responses are sent immediately instead of waiting to be batched. |
keepalive |
15 (seconds) |
listen()/serve() only; see Keepalive. |
max_connections |
0 (no limit) |
serve() only. |
An option name any of these functions doesn't recognise throws InvalidArgumentException
instead of being silently ignored. A context key escapes to raw stream context options
(anything stream_socket_server()/stream_socket_client() take, such as ssl):
Production
The phasync extension
phasync waits for sockets with stream_select(), which in PHP fails for any file descriptor
numbered 1024 or higher. A server with more than roughly 1,000 open connections hits that.
The phasync extension (MIT) replaces it with an epoll
poller without that limit.
Code written for phasync, like the examples here, works the same with the extension. Its
other job is making ordinary blocking code cooperate: inside phasync::run(), a library's
fread() / fwrite() on a blocking stream, file reads, DNS lookups, usleep(), PDO, mysqli and
curl suspend the coroutine instead of stalling every connection.
Release packages of phasync carry prebuilt binaries: run the server with
vendor/bin/phasync server.php instead of php server.php, or install the extension for every
SAPI with pie install phasync/ext-phasync.
JIT
PHP's JIT is off by default on the command line. For a server, turn it on:
Upgrading from 1.x
The package is renamed from phasync/server to phasync/net:
2.0 requires phasync 2.0 and has a new API, modelled on Go's net package:
| 1.x | 2.0 |
|---|---|
Server::serve($address, $handler) |
foreach (listen($address) as $peer => $conn), starting a coroutine per connection |
new TcpServer([...addresses]), foreach ($server->accept() ...) |
one listen() per address, foreach ($listener ...); see Several addresses |
TcpServer::getAddresses(): array |
$listener->addr(): string |
isClosed() |
gone: accept() throws IOException once the listener is closed |
TcpClient::connect() / connectUnix() |
dial('host:port') / dial('unix:///path') |
UdpServer::receive() yielding peer => [data, socket] |
foreach (listenPacket($address) as $peer => $data); reply with $conn->writeTo($data, $peer) |
Connections are no longer wrapped in AsyncStream: they are plain non-blocking streams. Wait
with phasync::readable() / phasync::writable() before reading or writing. The
$wrapStreams, $readBuffer and $writeBuffer options are gone.