高速公路管理订阅

时间:2018-05-07 09:24:30

标签: php websocket autobahn phpwebsocket thruway

我尝试通过Thruway设置一个可以管理多个组的websocket服务器。类似聊天应用程序的东西,每个客户端可以同时订阅一个或多个,并向整个聊天室广播消息。我设法用古老版本的Ratchet做到了,但由于它没有非常顺利,我想切换到高速公路。可悲的是,我无法找到管理团体的任何东西。到目前为止,我有以下作为websocket-manager,客户端正在使用当前版本的Autobahn | js(18.x)。

有没有人知道是否可以通过以下方式管理订阅组?

<?php

require_once __DIR__.'/../vendor/autoload.php';

use Thruway\Peer\Router;
use Thruway\Transport\RatchetTransportProvider;

$router = new Router();
$router->addTransportProvider(new RatchetTransportProvider("0.0.0.0", 9090));

$router->start();

1 个答案:

答案 0 :(得分:4)

通过ThruWay,事情与旧棘轮有点不同。首先,Thruway不是WAMP服务器。它只是一个路由器。所以它没有像旧的Rathcet那样的服务器实例让你包装所有服务器端功能。但它只会获取消息数据包,并route将它们转发到同一域中的其他会话,具体取决于它们的订阅。如果你曾经使用过socket.io,那么领域的想法类似于不同的连接,所以你可以限制你的会话或连接到一个命名空间或分割不同套接字实例的功能,如管理,访问者等。

在客户端使用autobahn(最新版本)订阅主题后,然后在该主题中发布,thruway将自动检测主题订阅者并在同一领域向他们发送消息。但是在旧棘轮中,你需要通过保留一系列可用频道来手动处理这个频道,并在订阅时将用户添加到每个频道,并通过迭代在主题中向这些用户广播消息。这真的很痛苦。

如果你想在服务器端使用RPC调用而不想在客户端包含你的一些东西,你仍然可以在服务器端使用一个名为internalClient的类。从概念上讲,内部客户端是另一个连接到您的高速客户端的会话,并在内部处理某些功能而不会暴露其他客户端。它接收消息包并在其中执行操作,然后将结果返回给请求的客户端连接。我花了一段时间才明白它是如何工作的,但一旦我弄清楚背后的想法更有意义。

这么少的代码可以更好地解释,

在你的路由器实例中你需要添加一个模块,(注意,在voxys / thruway包中的例子对于内部客户端来说有点混乱)

<强> server.php     

require __DIR__ . "/../bootstrap.php";
require __DIR__ . '/InternalClient.php';

$port = 8080;
$output->writeln([
    sprintf('Starting Sockets Service on Port [%s]', $port),
]);
$router = new Router();

$router->registerModule(new RatchetTransportProvider("127.0.0.1", $port));   // use 0.0.0.0 if you want to expose outside world

// common realm ( realm1 )
$router->registerModule(
    new InternalClient()    // instantiate the Socket class now
);

// administration realm (administration)
// $router->registerModule(new \AdminClient());

$router->start();

这将初始化Thruway路由器并将internalclient实例附加到它。现在在InternalClient.php文件中,您将能够访问实际路由以及当前连接的客户端。通过他们提供的示例,路由器不是实例的一部分,因此您只能使用新连接的会话ID属性。

<强> InternalClient.php

<?php

use Thruway\Module\RouterModuleInterface;
use Thruway\Peer\Client;
use Thruway\Peer\Router;
use Thruway\Peer\RouterInterface;
use Thruway\Logging\Logger;
use React\EventLoop\LoopInterface;

class InternalClient extends Client implements RouterModuleInterface
{
    protected $_router;

    /**
     * Contructor
     */
    public function __construct()
    {
        parent::__construct("realm1");
    }

    /**
     * @param RouterInterface $router
     * @param LoopInterface $loop
     */
    public function initModule(RouterInterface $router, LoopInterface $loop)
    {
        $this->_router = $router;

        $this->setLoop($loop);

        $this->_router->addInternalClient($this);
    }

    /**
     * @param \Thruway\ClientSession $session
     * @param \Thruway\Transport\TransportInterface $transport
     */
    public function onSessionStart($session, $transport)
    {
        // TODO: now that the session has started, setup the stuff

        echo "--------------- Hello from InternalClient ------------\n";
        $session->register('com.example.getphpversion', [$this, 'getPhpVersion']);

        $session->subscribe('wamp.metaevent.session.on_join',  [$this, 'onSessionJoin']);
        $session->subscribe('wamp.metaevent.session.on_leave', [$this, 'onSessionLeave']);
    }

    /**
     * Handle on new session joined.
     * This is where session is initially created and client is connected to socket server
     *
     * @param array $args
     * @param array $kwArgs
     * @param array $options
     * @return void
     */
    public function onSessionJoin($args, $kwArgs, $options) {
        $sessionId = $args && $args[0];
        $connectedClientSession = $this->_router->getSessionBySessionId($sessionId);
        Logger::debug($this, 'Client '. $sessionId. ' connected');
    }

    /**
     * Handle on session left.
     *
     * @param array $args
     * @param array $kwArgs
     * @param array $options
     * @return void
     */
    public function onSessionLeave($args, $kwArgs, $options) {

        $sessionId = $args && $args[0];

        Logger::debug($this, 'Client '. $sessionId. ' left');

        // Below won't work because once this event is triggered, client session is already ended
        // and cleared from router. If you need to access closed session, you may need to implement
        // a cache service such as Redis to access data manually.
        //$connectedClientSession = $this->_router->getSessionBySessionId($sessionId); 
    }

    /**
     * RPC Call messages
     * These methods will run internally when it is called from another client. 
     */
    private function getPhpVersion() {

        // You can emit or broadcast another message in this case
        $this->emitMessage('com.example.commonTopic', 'phpVersion', array('msg'=> phpVersion()));

        $this->broadcastMessage('com.example.anotherTopic', 'phpVersionRequested', array('msg'=> phpVersion()));

        // and return result of your rpc call back to requester
        return [phpversion()];
    }

    /**
     * @return Router
     */
    public function getRouter()
    {
        return $this->_router;
    }


    /**
     * @param $topic
     * @param $eventName
     * @param $msg
     * @param null $exclude
     */
    protected function broadcastMessage($topic, $eventName, $msg)
    {
        $this->emitMessage($topic, $eventName, $msg, false);
    }

    /**
     * @param $topic
     * @param $eventName
     * @param $msg
     * @param null $exclude
     */
    protected function emitMessage($topic, $eventName, $msg, $exclude = true)
    {
        $this->session->publish($topic, array($eventName), array('data' => $msg), array('exclude_me' => $exclude));
    }

}

上面的示例代码中很少有注意事项, - 为了在主题中接收消息,在客户端,您需要订阅该主题。 - 内部客户端可以在同一领域中发布/发布/广播任何主题,而无需任何订阅。 - 广播/发射功能不是原始高速公路的一部分,我想出了一些让我的出版物变得更容易的东西。 emit将发送消息包给每个人订阅主题,发件人除外。另一方面,广播不会排除发件人。

我希望这些信息有助于理解这个概念。

相关问题