moonda / moonws
基于 Ratchet 的基于 WebSocket 的项目的抽象模式。
v1.0.0
2016-06-20 15:20 UTC
Requires
- php: >=5.5.0
- cboden/ratchet: ^0.3.5
Requires (Dev)
- phpunit/phpunit: 4.8.*
This package is not auto-updated.
Last update: 2019-12-31 20:26:34 UTC
README
基于 Ratchet 的基于 WebSocket 的项目的抽象模式。
该项目定义了一个具有高重构能力的抽象模式(非常容易从现有项目集成,并且非常容易迁移/重构),以便构建轻量级且易于阅读的 WebSocket 服务器。
此模式旨在避免所谓的 “大意大利面式代码集群”,这在未经警告的开发者开始玩弄 WebSocket 时相当常见:代码集中化、相互依赖和循环模式通常是年轻 WebSocket 项目带来的大 noes。
但不必害怕。MoonWS 就在这里。
安装和需求
PHP 5.5.0 或更高版本是必需的。
此库可通过 composer 获取。只需输入
composer require moonda/moonws
没有其他要求。通常,这类服务器非常适合基于 Silex/Symfony 的应用程序,因为参数的“容器化”,但它几乎可以在任何地方工作。
使用方法
使用方法与从 Ratchet 创建 WS 消息组件非常相似。阅读文档。
您的主要服务器类将略有变化
<?php
class Chat extends WSEndpoint
{
/**
* The first argument is an array of controllers that should be used by the dispatcher,
* as follow :
* (string) controllerName => (AbstractWSController) controller
*
* Requests will then be mapped using the controller name and method name in the
* "action" field of the message, e.g :
* {
* "action" => "player/playTurn"
* }
* will call the public method "playTurn" from the controller
* attached to the key "player".
*/
public function __construct()
{
parent::__construct(array(
"chat" => new ChatController()
));
}
}
当然,您可以重写基本方法,例如 onOpen、onError 等... 然而,建议 不要 重写 onMessage 方法,因为它是整个模式的起点。
您的控制器类将如下所示
<?php
class ChatController extends AbstractWSController
{
public function sayHelloToMyFriends(ConnectionInterface $conn, $msg){
/**
* @var $client ConnectionInterface
*/
foreach ($this->endpoint->getCollections()->getClients() as $client){
$this->sendMessageTo($client, array(
"me" => $conn->{'resourceId'},
"my_message" => "Hello Friend !",
"what_i_sent" => $msg
));
}
}
}
快乐地启动您的新服务器
<?php
$server = IoServer::factory(
new HttpServer(
new WsServer(
new Chat()
)
),
9999
);
然后可以调用 sayHelloToFriends 方法从客户端调用
var ws = new WebSocket("ws://127.0.0.1:9999");
ws.send(JSON.stringify({
"action": "chat/sayHelloToMyFriends",
"yeaha": "yeah !"
}));