francium / diffsocket
一个用于在单个服务器中提供多个WebSocket服务的PHP库
v0.1.1
2016-05-30 17:30 UTC
Requires
- php: >=5.3.9
- cboden/ratchet: >=0.3
Requires (Dev)
- francium/process: >=0.3.2
- phpunit/phpunit: >=3.7
- textalk/websocket: 1.0.*
This package is not auto-updated.
Last update: 2024-09-14 18:47:43 UTC
README
一个通过单个端口提供多个WebSocket服务的PHP库。
通常,如果您想运行多个服务,您需要在不同的端口上运行WebSocket服务器。使用DiffSocket,您可以使用单个端口为不同的服务。
安装
composer require francium/diffsocket
为什么不使用不同的端口为不同的服务?
一些托管服务提供商不允许您在多个端口上进行绑定,尤其是如果您使用的是免费计划。例如 OpenShift。
我创建了DiffSocket,因为我的WebSocket服务器托管在OpenShift上,需要一种方法通过单个端口提供多个WebSocket服务。
演示
这些不同的服务通过单个WebSocket端口(ws-subins.rhcloud.com:8000)提供。
用法
服务器
DiffSocket使用Ratchet作为WebSocket服务器。您应该学习Ratchet来创建服务。
-
配置服务器
<?php $DS = new Fr\DiffSocket(array( "server" => array( "host" => "127.0.0.1", "port" => "8000" ) ));
-
要添加新的服务,在命名空间
Fr\DiffSocket\Service
下创建一个类SayHello.php
namespace Fr\DiffSocket\Service; use Ratchet\MessageComponentInterface; use Ratchet\ConnectionInterface; class SayHello implements MessageComponentInterface { public function onOpen(ConnectionInterface $conn){ echo "New Connection - " . $conn->resourceId; } public function onClose(ConnectionInterface $conn){} public function onError(ConnectionInterface $conn, $error){} public function onMessage(ConnectionInterface $conn, $message){ $conn->send("Hello"); } }
然后,您应该通过以下方式将服务注册到DiffSocket中
$DS->addService("say-hello", "path/to/SayHello.php");
-
然后,添加运行服务器的代码
$DS->run();
在创建对象时,您也可以将服务作为数组添加
$DS = new Fr\DiffSocket(array( "server" => array( "host" => "127.0.0.1", "port" => "8000" ), "services" => array( "say-hello" => __DIR__ . "/services/SayHello.php", "chat" => __DIR__ . "/services/Chat.php", "game" => __DIR__ . "/services/GameServer.php" ) ));
客户端
只需在URL中将服务名称作为GET参数添加。注意在?
之前使用/
ws://ws.example.com:8000/?service=say-hello ws://ws.example.com:8000/?service=chat ws://ws.example.com:8000/?service=game
JavaScript示例
var sayHelloWS = new WebSocket("ws://ws.example.com:8000/?service=say-hello"); var chatWS = new WebSocket("ws://ws.example.com:8000/?service=chat"); var gameWS = new WebSocket("ws://ws.example.com:8000/?service=game");
如果未传递GET参数service
或传递的值不匹配任何可用的服务,那么DiffSocket将拒绝连接并关闭它。