PHP code example of phasync / server

1. Go to this page and download the library: Download phasync/server library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

phasync / server example snippets


use function phasync\Net\listen;

phasync::run(function () {
    $listener = listen('0.0.0.0:8080');

    foreach ($listener as $peer => $conn) {
        phasync::go(function () use ($conn, $peer) {
            $request = fread(phasync::readable($conn), 65536);

            fwrite(phasync::writable($conn),
                "HTTP/1.1 200 OK\r\n" .
                "Connection: close\r\n" .
                "Content-Length: " . strlen("Hello, $peer!") . "\r\n" .
                "\r\n" .
                "Hello, $peer!"
            );
            fclose($conn);
        });
    }
});

$conn = $listener->accept($peer); // like stream_socket_accept(): $peer is optional

foreach (['0.0.0.0:80', '0.0.0.0:8080'] as $address) {
    phasync::go(function () use ($address) {
        foreach (listen($address) as $peer => $conn) {
            phasync::go(fn () => handle($conn, $peer));
        }
    });
}

phasync::channel($connections, $newConnection);

foreach (['0.0.0.0:80', '0.0.0.0:8080'] as $address) {
    phasync::go(function () use ($address, $newConnection) {
        foreach (listen($address) as $peer => $conn) {
            $newConnection->write([$peer, $conn]);
        }
    });
}

phasync::go(function () use ($connections) {
    foreach ($connections as [$peer, $conn]) {
        phasync::go(fn () => handle($conn, $peer));
    }
});

$listener = listen('unix:///run/myapp.sock');

$listener = Listener::fromStream($stream); // a listening stream socket, made non-blocking

listen('0.0.0.0:8080', ['keepalive' => 30]);

$listener = listen('127.0.0.1:0');
echo $listener->addr(); // 127.0.0.1:43127

phasync\Net\listen(string $address, array $options = []): Listener

$listener->accept(?string &$peer = null)      // connection; $peer is set to its address; IOException once closed
foreach ($listener as $peer => $conn)         // until the listener is closed
$listener->close(): void
$listener->addr(): string
Listener::fromStream($stream): Listener       // wrap a listening socket another process created

use function phasync\Net\serve;

phasync::run(function () {
    foreach (serve('0.0.0.0:8080') as $peer => $conn) {
        phasync::go(function () use ($conn) {
            while ('' !== ($data = $conn->read())) {
                $conn->write($data); // echo
            }
            $conn->close();
        });
    }
});

use function phasync\Net\dial;

phasync::run(function () {
    $conn = dial('example.com:80');

    $conn->write("GET / HTTP/1.0\r\nHost: example.com\r\n\r\n");
    while ('' !== ($data = $conn->read())) {
        echo $data;
    }
    $conn->close();
});

dial('tls://example.com:443');   // TLS; the certificate is checked against the host name
dial('unix:///run/app.sock');    // Unix domain socket
dial('[::1]:8080', timeout: 5);  // the timeout covers lookup, connect and TLS handshake

// context escapes to raw stream context options, such as a TLS trust store
dial('tls://example.com:443', options: ['context' => ['ssl' => ['cafile' => '/path/ca.pem']]]);

phasync\Net\dial(string $address, float $timeout = 30, array $options = []): Duplex

use function phasync\Net\listenPacket;

phasync::run(function () {
    $conn = listenPacket('0.0.0.0:9000');

    foreach ($conn as $peer => $data) {
        $conn->writeTo("Echo: $data", $peer);
    }
});

phasync\Net\listenPacket(string $address, array $options = []): PacketConn

$conn->readFrom(int $maxLength = 65536): array{string, string}  // [datagram, peer]; IOException once closed
foreach ($conn as $peer => $data)                               // until the socket is closed
$conn->writeTo(string $data, string $address): int|false
$conn->close(): void
$conn->addr(): string

use phasync\Net\Dns;
use phasync\Net\DnsRecordType;

phasync::run(function () {
    // Default: tries A (IPv4) first, then AAAA (IPv6).
    // Returns a random IP when there are several records.
    $ip = Dns::resolve('example.com');

    $allIps = Dns::resolveAll('example.com', DnsRecordType::A);
    $ipv4   = Dns::resolve('example.com', DnsRecordType::A);
    $ipv6   = Dns::resolve('example.com', DnsRecordType::AAAA);
});

Dns::resolve(string $hostname, DnsRecordType $type = DnsRecordType::ANY, float $timeout = 2.0): ?string
Dns::resolveAll(string $hostname, DnsRecordType $type = DnsRecordType::ANY, float $timeout = 2.0): array
Dns::clearCache(): void

$listener = listen('0.0.0.0:8080', [
    'tcp_nodelay' => false,
    'context'     => ['socket' => ['ipv6_v6only' => false]],
]);

// 1.x
Server::serve('tcp://127.0.0.1:8080', function ($stream, $peer) {
    // handle connection
});

// 2.0
foreach (listen('127.0.0.1:8080') as $peer => $conn) {
    phasync::go(fn () => /* handle connection */);
}
bash
php -d opcache.enable_cli=1 -d opcache.jit=tracing -d opcache.jit_buffer_size=128M server.php