phrity/websocket

WebSocket 客户端和服务器

3.1.0 2024-07-09 11:00 UTC

README

Build Status Coverage Status

此库包含用于PHP的WebSocket客户端和服务器。替代 textalk/websocket

客户端和服务器提供用于读取和写入WebSocket流的函数。

此仓库替代了已废弃的 textalk/websocket 仓库,并由Sören Jensen维护,他自 v1.3 版本以来一直在维护原始版本。

文档

安装

首选的安装方法是使用 Composer

composer require phrity/websocket

客户端

客户端 可在WebSocket流上读取和写入。它内部支持升级握手和隐式关闭以及ping/pong操作。

为请求/响应策略设置WebSocket客户端

$client = new WebSocket\Client("wss://echo.websocket.org/");
$client
    // Add standard middlewares
    ->addMiddleware(new WebSocket\Middleware\CloseHandler())
    ->addMiddleware(new WebSocket\Middleware\PingResponder())
    ;

// Send a message
$client->text("Hello WebSocket.org!");

// Read response (this is blocking)
$message = $client->receive();
echo "Got message: {$message->getContent()} \n";

// Close connection
$client->close();

为连续订阅设置WebSocket客户端

$client = new WebSocket\Client("wss://echo.websocket.org/");
$client
    // Add standard middlewares
    ->addMiddleware(new WebSocket\Middleware\CloseHandler())
    ->addMiddleware(new WebSocket\Middleware\PingResponder())
    // Listen to incoming Text messages
    ->onText(function (WebSocket\Client $client, WebSocket\Connection $connection, WebSocket\Message\Message $message) {
        // Act on incoming message
        echo "Got message: {$message->getContent()} \n";
        // Possibly respond to server
        $client->text("I got your your message");
    })
    ->start();

服务器

服务器 是一个多连接监听服务器。它内部支持升级握手和隐式关闭以及ping/pong操作。

为连续监听设置WebSocket服务器

$server = new WebSocket\Server();
$server
    // Add standard middlewares
    ->addMiddleware(new WebSocket\Middleware\CloseHandler())
    ->addMiddleware(new WebSocket\Middleware\PingResponder())
    // Listen to incoming Text messages
    ->onText(function (WebSocket\Server $server, WebSocket\Connection $connection, WebSocket\Message\Message $message) {
        // Act on incoming message
        echo "Got message: {$message->getContent()} \n";
        // Possibly respond to client
        $connection->text("I got your your message");
    })
    ->start();

许可证

ISC许可证