6phere/php-websocket

异步WebSocket客户端

v1.1.5 2019-07-31 14:41 UTC

This package is auto-updated.

Last update: 2024-09-28 17:07:26 UTC


README

PHP的异步WebSocket客户端库。支持HyBi,以及Hixie #76(没有意义)。

这个库纯粹是为了作为一个客户端,因为大多数可用的WS客户端也包含服务器,并且非常臃肿。

安装

使用composer

composer require sixphere\php-websocket   

用法

由于这个库非常适合作为异步应用,它被构建为使用React事件循环和解析器,因为它们很可能已经在您的项目中,并且这允许您附加到同一个循环。

$loop = \React\EventLoop\Factory::create();
$dns_factory = new React\Dns\Resolver\Factory();
$resolver = $dns_factory->createCached('8.8.8.8', $loop);

$client = new \Sixphere\WebSocket\Client('ws://127.0.0.1:1337/chat', $loop, $resolver);

//Most WS servers will complain/forbid if there is no origin header
$client->setOrigin('127.0.0.1');

$client->connect();


$client->on('stateChange', function($newState){
    echo "State changed to: $newState\n";
});

$client->on('message', function($message) use ($client){
    echo "New message: \n";
    echo $message;
    
    $client->send('This is a response message');
});

$loop->run();

其他可用的事件有 connectingconnectdisconnectingdisconnect

通过URI支持HTTP基本认证,格式为 user:pass@host

任何反馈都十分欢迎

这是从以下地址分支的:https://github.com/calcinai/bolt