innmind/socket

PHP socket 函数包装器

6.1.0 2023-09-17 13:14 UTC

This package is auto-updated.

Last update: 2024-09-17 15:31:19 UTC


README

Build Status codecov Type Coverage

innmind/stream之上构建,专门用于与套接字协同工作。

安装

composer require innmind/socket

用法

Unix 套接字

服务器示例

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);

上面的示例在/tmp/my-socket.sock创建一个套接字,并将无限期等待。一旦有可用连接,它将调用$doSomething()

客户端示例

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
);

这将简单地连接到上面声明的套接字服务器,并发送数据hello there!

如果您想读取服务器发送回来的数据,应使用流Select以等待数据到达。

互联网套接字

与Unix套接字相同的逻辑,但服务器和客户端的构建方式不同。

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