chrome-php/wrench

简单的PHP WebSocket实现

v1.6.0 2024-03-17 22:37 UTC

This package is auto-updated.

Last update: 2024-09-18 12:36:16 UTC


README

Latest Stable Version License

简单的PHP WebSocket实现。

安装

此库可以使用Composer安装,并在Packagist上以chrome-php/chrome的形式提供

$ composer require chrome-php/wrench

目前仅支持PHP 7.4-8.3

使用方法

这将在127.0.0.1:8000上创建一个服务器,该服务器有一个应用程序,监听对ws://localhost:8000/echows://localhost:8000/chat的WebSocket请求

服务器

// An example application, that just echoes the received
// data back to the connection that sent it
$app = new class implements \Wrench\Application\DataHandlerInterface
{
    public function onData(string $data, \Wrench\Connection $connection): void
    {
        $connection->send($data);
    }
};

// A websocket server, listening on port 8000
$server = new \Wrench\BasicServer('ws://localhost:8000', [
    'allowed_origins' => [
        'mysite.com',
        'mysite.dev.localdomain'
    ],
]);

$server->registerApplication('echo', $app);
$server->registerApplication('chat', new \My\ChatApplication());
$server->setLogger($monolog); // PSR3
$server->run();

客户端

// A client side example, that sends a string and will receive
// the data back to the connection that sent it
$client = new Client('ws://localhost:8000', 'http://localhost:8000');
$client->connect();
$client->sendData('hello');
$response = $client->receive()[0]->getPayload();
$client->disconnect();

贡献

有关贡献详情,请参阅CONTRIBUTING.md

许可证

本项目采用MIT许可证(MIT)许可。