timostamm/websocket-server
Composer 安装命令:
composer require timostamm/websocket-server
包简介
A simple nonblocking server dedicated to websockets.
README 文档
README
A simple nonblocking server dedicated to websockets.
- upgrades HTTP requests
- routes HTTP requests to simple websocket-controllers
- can filter HTTP requests
- passes Autobahn WebSocket Testsuite
- does NOT implement compression
- works well with apache >= 2.4
- installable via
composer require timostamm/websocket-server - minimal dependencies (react/socket, ratchet/rfc6455, guzzlehttp/psr7)
- graceful shutdown via signals (or manually)
Credits for the websocket protocol implementation go to ratchet/rfc6455.
Example
$loop = Factory::create(); // use a react event loop // start server $server = new WebsocketServer($loop, [ 'uri' => '127.0.0.1:23080' ]); // add a controller $server->route([ 'match' => '/example/*', 'controller' => new class() implements ControllerInterface { function onOpen(WebSocket $connection): void { print $connection . ' connected. Sending a "Hello".' . PHP_EOL; $connection->send('Hello'); } function onMessage(WebSocket $from, string $payload, bool $binary): void { print $from . ' sent: ' . $payload . PHP_EOL; } function onClose(WebSocket $connection, ?Throwable $error): void { print $connection . ' disconnected.' . PHP_EOL; } } ]); // This error handler will be called when an exception was thrown // by a filter, a controller method or the underlying tcp server. $server->on('error', function (Throwable $error) { print 'Server error: ' . $error->getMessage() . PHP_EOL; }); $loop->run(); // the react event loop processes socket connections
Routing
This route will match paths starting with /example/.
$server->route([ 'match' => '/example/*', 'controller' => $controller ]);
Placeholders are implemented using fnmatch().
This route will match any path:
$server->route([ 'controller' => $controller ]);
This route will deny the websocket handshake if the client did not specifiy one of the subprotocols:
$server->route([ 'protocols' => ['soap'], 'controller' => $controller ]);
Request filters
This filter responds with a HTTP 403
$server->filter('example/403', function () { throw ResponseException::create(403); });
This filter modifies the request
$server->filter('example/add-attribute', function (ServerRequestInterface $request) { return $request->withAttribute('X-filter', 'passed'); });
This filter allows only the specified origins
$server->filter('example/origin', new OriginFilter(['example.com']));
You can provide your or RequestMatcherInterface and RequestFilterInterface
implementations. Filters can also be added via route():
$server->route([ 'match' => '/example/*', 'filter' => function(ServerRequestInterface $request){ if ($request->getRequestTarget() === '/example/forbidden') { throw ResponseException::create(403); } } 'controller' => ... ]);
Authentication
This library does not provide session integration, but provides support for bearer token authentication.
Extend AbstractTokenAuthenticator with your token verification code and
return a user object. The user will be be available in the request attribute
"user". If no token is present, the user attribute will be empty.
Use AuthorizationFilter to check whether a user is present. Supply a
$checkUser function to check whether the user is authorized.
See examples/token-auth.php
Apache config
Add the following to a .htaccess file to proxy all requests with a Upgrade: websocket header to the websocket server.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP:Upgrade} =websocket [NC]
RewriteRule ^(.*)$ ws://127.0.0.1:23080/$1 [P,L]
</IfModule>
Javascript
var ws = new WebSocket("ws://localhost:23080/hello/foo"); ws.onmessage = function (event) { console.log("message", event.data); };
More controller features
You can implement one or more of the following interfaces to get access to the loop, clients connected to this controller, etc.
class MyCtrl implements ControllerInterface, LoopAwareInterface ConnectionListAwareInterface, OnShutDownInterface, OnLastCloseInterface, OnFirstOpenInterface { function setLoop(\React\EventLoop\LoopInterface $loop, callable $exceptionHandler): void { print 'Got loop.' . PHP_EOL; } function setConnections(\SplObjectStorage $webSockets): void { print 'Got connection list.' . PHP_EOL; } function onShutDown(): PromiseInterface { // Will be called when the server is asked to shutdown. // Use this hook to finish important tasks, then resolve the promise. } function onLastClose(WebSocket $socket): void { print 'Last connection closed.' . PHP_EOL; } function onFirstOpen(WebSocket $socket): void { print 'First connection opened.' . PHP_EOL; } function onOpen(WebSocket $socket): void { print $socket . ' connected. Sending a "Hello".' . PHP_EOL; $socket->send('Hello'); } function onMessage(WebSocket $from, string $payload, bool $binary): void { print $from . ' received: ' . $payload . PHP_EOL; } function onClose(WebSocket $socket): void { print $socket . ' disconnected.' . PHP_EOL; } function onError(WebSocket $socket, \Throwable $error): void { print $socket . ' error: ' . $error->getMessage() . PHP_EOL; } }
timostamm/websocket-server 适用场景与选型建议
timostamm/websocket-server 是一款 基于 HTML 开发的 Composer 扩展包,目前已累计 151 次下载、GitHub Stars 达 0, 最近一次更新时间为 2018 年 09 月 10 日, 在 PHP 生态内属于活跃度较高的组件。
我们在过去多个企业项目中使用过 timostamm/websocket-server 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 timostamm/websocket-server 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
统计信息
- 总下载量: 151
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 8
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2018-09-10