PHP code example of innmind / socket

1. Go to this page and download the library: Download innmind/socket 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/ */

    

innmind / socket example snippets


use Innmind\Socket\{
    Server\Unix,
    Address\Unix as Address,
};
use Innmind\TimeContinuum\Earth\ElapsedPeriod;
use Innmind\Stream\Watch\Select;

$server = Unix::recoverable(Address::of('/tmp/my-socket'))->match(
    static fn($server) => $server,
    static fn() => throw new \RuntimeException('Unable to create socket'),
);
$select = Select::timeoutAfter(new ElapsedPeriod(100))
    ->forRead($server);

do {
    $select()
        ->flatMap(fn($ready) => $ready->toRead()->find(fn($stream) => $stream === $server))
        ->flatMap(fn($server) => $server->accept())
        ->match(
            static fn($incomingConnection) => $doSomething($incomingConnection),
            static fn() => null, // no incoming connection within the last 100 milliseconds
        )
} while (true);

use Innmind\Socket\{
    Client\Unix,
    Address\Unix as Address,
};

$client = Unix::of(Address::of('/tmp/my-socket'))->match(
    static fn($client) => $client,
    static fn() => throw new \RuntimeException('Unable to connect to socket'),
);
$client->write(Str::of('hello there!'))->match(
    static fn($client) => $continueToDoSomething($client),
    static fn($error) => null, // do something else when it failed to write to the socket
);

use Innmind\Socket\{
    Server\Internet,
    Internet\Transport,
};
use Innmind\IP\IPv4;
use Innmind\Url\Authority\Port;

$server = Internet::of(
    Transport::tcp(),
    IPv4::of('127.0.0.1'),
    Port::of(80),
);
//this will listen for incoming tcp connection on the port 80

use Innmind\Socket\{
    Client\Internet,
    Internet\Transport,
};
use Innmind\Url\Url;

$client = Internet::of(
    Transport::tcp(),
    Url::of('//127.0.0.1:80')->authority(),
);
//this will connect to a local socket on port 80