paragi/php-websocket-client

WebSocket客户端

1.0.0 2022-03-22 21:49 UTC

This package is auto-updated.

Last update: 2024-09-17 23:35:24 UTC


README

使用PHP连接到WebSocket服务。这3种方法用于WebSocket协商、连接和处理hybi10帧编码。

注意:与ratchetphp/Pawl库不同,这是一个同步库,可以在Symfony等阻塞内核中使用。

示例1

try {
   $sp = new \Paragi\PhpWebsocket\Client('echo.websocket.org',80) );
   $sp->write("hello server");
   echo "Server responded with: " . $sp->read();
} catch (\Paragi\PhpWebsocket\ConnectionException $e) {
   echo "Something gets wrong ".$e->getMessage();
}

示例2,使用会话cookie和设置超时

try {
    $headers = ["Cookie: SID=".session_id()];
    $sp = new \Paragi\PhpWebsocket\Client('echo.websocket.org',80,$headers,$errstr,16);
    $bytes_written = $sp->write("hello server");
    $data = $sp->read();
    echo "Server responded with: ". $data;
} catch (\Paragi\PhpWebsocket\ConnectionException $e) {
   echo "Something gets wrong ".$e->getMessage();
}

示例3,使用SSL

try {
    $sp = new \Paragi\PhpWebsocket\Client('echo.websocket.org',443,'',$errstr, 10,true) ) {
    $sp->write("hello server");
    echo "Server responded with: " . $sp->read();
} catch (\Paragi\PhpWebsocket\ConnectionException $e) {
   echo "Something gets wrong ".$e->getMessage();
}

客户端类

构造函数

打开WebSocket连接

__construct(string $host [, int $port [, array $additional_headers [, string &error_string [, int $timeout [, resource $context]]]]] )

host 主机URL。可以是域名,如 www.example.com,或IP地址,如本地主机:127.0.0.1

port 服务器端口号

headers(可选)附加到请求的额外HTTP头。例如解析会话cookie。

error_string(可选)用于存储错误消息的引用变量,如果有任何错误。

timeout(可选)读取操作等待服务器回答的最大时间(秒)。默认值为10秒。

context(可选)使用stream_context_create()创建的流上下文资源,用于设置各种套接字流选项。

write

通过WebSocket向服务器发送数据,使用hybi10帧编码。

int write(string $data [,boolean $final])

data 要传输到服务器的数据

final(可选)指示此块是否为请求的最后一个数据块。默认true

read

通过WebSocket从服务器读取数据,使用hybi10帧编码。

string read([string &error_string])

error_string(可选)用于存储错误消息的引用变量,如果有任何错误。

注意

  • 此实现等待数据的最后一个块,然后返回。
  • 在处理/忽略其他类型的包的同时读取数据

异常

如果发生错误(连接、写入、读取...),将抛出ConnectionException。请捕获所有异常以返回完整的消息(以下是在Symfony环境中的示例)

try {
    $sp = new \Paragi\PhpWebsocket\Client($this->localIp, $this->wsPort, ['X-Pusher: Symfony']);
    $sp->write($data);
    $reading = $sp->read();
    $ret = "Server responded with: $reading";

    return new JsonResponse(['level' => 'success', 'message' => $ret], Response::HTTP_OK);
} catch (ConnectionException $ex) {
    return new JsonResponse(['level' => 'error', 'message' => $ex->getMessage()], Response::HTTP_SERVICE_UNAVAILABLE);
}

测试

测试正在针对使用Ratchet实现的本地echo服务器运行。您必须在另一个进程中手动启动服务器。

$ php tests/bin/echoserver.php

现在您可以启动PhpUnit

$ vendor/bin/phpunit 

代码覆盖率

使用PhpDbg,只需启动

$ phpdbg -qrr vendor/bin/phpunit
$ firefox .coverage/index.html

贡献

请告诉我代码中是否有任何问题。任何贡献都是接受的,如果代码看起来不错,不是冗余的,并且是合理的。

许可:MIT:免费

待办事项

  • 实现100%代码覆盖率