mix / websocket
WebSocket server and client based on Swoole coroutine
Installs: 6 276
Dependents: 5
Suggesters: 0
Security: 0
Stars: 3
Watchers: 2
Forks: 0
Open Issues: 0
Requires
- php: >=7.0.0
- ext-swoole: >=4.4.15
- mix/http-message: ~3.0.0
Requires (Dev)
- mix/vega: ^3.0
- phpunit/phpunit: ^7.0.0
This package is auto-updated.
Last update: 2024-10-29 05:40:35 UTC
README
OpenMix 出品:https://openmix.org
Mix WebSocket
PHP WebSocket server and client based on Swoole coroutine
基于 Swoole 协程的 PHP WebSocket 服务器与客户端
Overview
该 WebSocket 支持处理服务器和客户端,服务器基于 Swoole 单进程协程 Swoole\Coroutine\Http\Server
驱动,没有多进程那些复杂的作用域和生命周期概念,开发体验和 Golang 一致,简单又高效。
推荐搭配以下数据库使用 (支持协程和连接池):
推荐搭配以下库处理 Subscribe:
技术交流
知乎:https://www.zhihu.com/people/onanying
官方QQ群:284806582
, 825122875
敲门暗号:ws
Installation
- Swoole >= 4.4.15: https://wiki.swoole.com/#/environment
composer require mix/websocket
服务器 Server
在 Mix Vega 中使用 (只支持 Swoole 单进程协程)
$upgrader = new Mix\WebSocket\Upgrader(); $vega = new Mix\Vega\Engine(); $vega->handle('/websocket', function (Mix\Vega\Context $ctx) use ($upgrader) { // 升级连接 $conn = $upgrader->upgrade($ctx->request, $ctx->response); // 接收消息 $in = $conn->readMessage(); var_dump($in->data); // 发送消息 $out = new Swoole\WebSocket\Frame(); $out->data = sprintf('hello, %s', $in->data); $conn->send($out); $conn->close(); })->methods('GET');
在 Swoole 原生中使用 (只支持单进程协程)
Swoole\Coroutine\run(function () { $upgrader = new Mix\WebSocket\Upgrader(); $server = new Swoole\Coroutine\Http\Server('0.0.0.0', 9502, false); $server->handle('/websocket', function (Swoole\Http\Request $request, Swoole\Http\Response $response) use ($upgrader) { // 升级连接 $conn = $upgrader->upgradeRaw($request, $response); // ... }); $server->start(); });
获取当前连接数
$total = $upgrader->count();
关闭全部连接
$upgrader->closeAll();
客户端 Client
可以连接任何 websocket v13 的服务器
$cli = Mix\WebSocket\Client('ws://127.0.0.1:9502/websocket'); // 发送消息 $out = new Swoole\WebSocket\Frame(); $out->data = 'xiaoming'; $cli->writeMessage($out); // 接收消息 $in = $cli->readMessage(); var_dump($in->data); $cli->close();
License
Apache License Version 2.0, http://www.apache.org/licenses/