webnarmin/amphp-websocket-server
Composer 安装命令:
composer require webnarmin/amphp-websocket-server
包简介
Authenticated Amp WebSocket transport runtime with user-aware gateway and control HTTP.
README 文档
README
Authenticated WebSocket transport runtime on top of Amp.
This package provides:
- WebSocket server bootstrap using
amphp/websocket-server. - Authentication for WebSocket clients and HTTP control requests.
- Strict JSON message envelopes.
- Explicit action routing.
- User-aware gateway for direct, multicast and broadcast delivery.
- HTTP control endpoints for pushing messages from another process.
It does not provide application-level chat flows, UI rendering, persistence, rooms, bot logic or framework-specific abstractions. Libraries such as ChatFlow can use this package as a transport layer.
Installation
composer require webnarmin/amphp-websocket-server
Quick Start
use webnarmin\AmphpWS\ActionRouter; use webnarmin\AmphpWS\Configurator; use webnarmin\AmphpWS\Protocol\ResponseEnvelope; use webnarmin\AmphpWS\Simple\SimpleAuthenticator; use webnarmin\AmphpWS\WebSocketServer; $router = new ActionRouter(); $router->on('echo', static function ($user, $message): ResponseEnvelope { return ResponseEnvelope::success([ 'message' => 'Echo: ' . ($message->getPayload()['message'] ?? ''), ]); }); $server = new WebSocketServer( new Configurator([ 'websocket' => ['host' => '127.0.0.1', 'port' => 1337], 'allow_origins' => ['http://127.0.0.1:8000'], ]), new SimpleAuthenticator('control-http-auth-token', 'websocket-signing-secret'), $router, ); $server->run();
Message Protocol
Clients send JSON objects:
{
"action": "echo",
"payload": {"message": "Hello"},
"requestId": "req-1",
"metadata": {"source": "browser"}
}
Rules:
actionis required and must be a non-empty string.payloadis optional and must be a JSON object when present.requestIdis optional and must be a non-empty string when present.metadatais optional and must be a JSON object when present.
Server responses use:
{
"status": "success",
"payload": {"message": "Echo: Hello"},
"requestId": "req-1"
}
Errors use:
{
"status": "error",
"payload": {},
"requestId": "req-1",
"error": {"code": "unsupported_action", "message": "Action 'x' is not supported."}
}
Standard error codes:
invalid_jsoninvalid_messageunsupported_actionhandler_failedauthentication_failedinvalid_control_request
Action Handlers
Handlers may be callables or implement MessageHandlerInterface.
$router->on('sum', static function ($user, $message): ResponseEnvelope { $numbers = $message->getPayload()['numbers'] ?? []; return ResponseEnvelope::success([ 'result' => is_array($numbers) ? array_sum($numbers) : 0, ]); });
Return null when no response should be sent. Return ResponseEnvelope::success([]) when an explicit empty success response should be sent.
Authentication
Implement Authenticator:
interface Authenticator { public function authenticateControlHttp(Request $request): bool; public function authenticateWebSocket(Request $request): ?WebsocketUser; }
WebsocketUser::getId() returns a non-null positive integer. If WebSocket authentication fails, the client is closed with policy violation code 1008.
SimpleAuthenticator is a minimal HMAC-signed token example. For production systems, implement Authenticator against your own session, API token or identity provider.
Gateway
Use getGateway() to send messages to authenticated users:
$server->getGateway()->sendText(123, 'Hello user'); $server->getGateway()->multicastText('Hello team', [123, 456]); $server->getGateway()->broadcastText('Hello everyone', excludedUserIds: [123]);
If a user has no active client, sending is a no-op handled by Amp's gateway. Invalid user ids are rejected with GatewayException.
HTTP Control
Authenticated POST endpoints:
/send-text/broadcast-text/broadcast-binary/multicast-text/multicast-binary
Successful response:
{"status":"success"}
Error response:
{"status":"error","error":{"code":"invalid_control_request","message":"payload must be a string."}}
Use WebsocketControlHttpClient from CLI or workers:
$result = $client->sendText(123, 'Hello'); if (!$result->isSuccess()) { echo $result->getMessage(); }
Lifecycle Hooks
ServerHooks supports optional callbacks:
- authenticated: called after a client is authenticated and registered.
- disconnected: called when a registered client disconnects.
- invalidMessage: called when inbound JSON/protocol validation fails.
- unhandledException: called for authentication and handler/runtime failures.
Examples
example/server.phpstarts a router-based server.example/public/index.phpis a browser test client.example/broadcast_from_cli.phpsends a control HTTP broadcast.
Quality
composer check composer cs-check
webnarmin/amphp-websocket-server 适用场景与选型建议
webnarmin/amphp-websocket-server 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 10 次下载、GitHub Stars 达 1, 最近一次更新时间为 2024 年 06 月 29 日, 在 PHP 生态内属于活跃度较高的组件。
我们在过去多个企业项目中使用过 webnarmin/amphp-websocket-server 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 webnarmin/amphp-websocket-server 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
统计信息
- 总下载量: 10
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 1
- 点击次数: 14
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2024-06-29