Проблемы с Ratchet WAMP Component

Краткое объяснение...

Я пытаюсь настроить сервер Ratchet Web Socket и у меня возникли некоторые проблемы. Вот что я пытаюсь достичь:

На моем сайте есть счетчик, который показывает, сколько пользователей зарегистрировалось на сайте. Я бы хотел, чтобы этот счетчик обновлялся всякий раз, когда другие пользователи регистрируются на сайте. Simples...

Что я пробовал

Я использую Ratchet только около 24 часов, поэтому мой опыт крайне ограничен, чтобы не сказать больше, но, тем не менее, я внимательно прочитал документацию и считаю, что я на правильном пути.

Вот мой код:

нажимной server.php

// Autoload any required libraries
require(dirname(__DIR__).'/vendor/autoload.php');

// Initiate the loop and pusher
$loop   = React\EventLoop\Factory::create();
$pusher = new _sockets\pusher;

// Listen for the web server to make a ZeroMQ push
$context = new React\ZMQ\Context($loop);
$pull = $context->getSocket(ZMQ::SOCKET_PULL);

// Binding to 127.0.0.1 means the only client that can connect is itself
$pull->bind('tcp://127.0.0.1:5555');
$pull->on('message', array($pusher,'message'));

// Set up the web socket server for the clients
$web_socket = new React\Socket\Server($loop);

// Binding to 0.0.0.0 means remotes can connect
$web_socket->listen(8080,'0.0.0.0');
$web_server = new Ratchet\Server\IoServer(
    new Ratchet\Http\HttpServer(
        new Ratchet\WebSocket\WsServer(
            new Ratchet\Wamp\WampServer(
                $pusher
            )
        )
    ),
    $web_socket
);

// Run the loop
$loop->run();

pusher.php

namespace _sockets;
use Ratchet\ConnectionInterface;
use Ratchet\Wamp\WampServerInterface;

class pusher implements WampServerInterface {
    /**
     * A lookup of all the topics clients have subscribed to
     */
    protected $subscribedTopics = array();

    public function onSubscribe(ConnectionInterface $conn, $topic) {
        $this->subscribedTopics[$topic->getId()] = $topic;
    }
    public function onUnSubscribe(ConnectionInterface $conn, $topic){
    }
    public function onOpen(ConnectionInterface $conn){
    }
    public function onClose(ConnectionInterface $conn){
    }
    public function onCall(ConnectionInterface $conn, $id, $topic, array $params){
    }
    public function onPublish(ConnectionInterface $conn, $topic, $event, array $exclude, array $eligible){
    }
    public function onError(ConnectionInterface $conn, \Exception $e){
    }
    public function message($data){

        $data = json_decode($data,true);

        // If the lookup topic object isn't set there is no one to publish to
        if(!array_key_exists($data['category'],$this->subscribedTopics)) {
            return;
        }

        $topic = $this->subscribedTopics[$data['category']];

        // re-send the data to all the clients subscribed to that category
        $topic->broadcast($data);
    }
}

Фрагмент из скрипта регистрации

// Push the sign up notice to all connections
$context = new ZMQContext();
$socket = $context->getSocket(ZMQ::SOCKET_PUSH);
$socket->connect("tcp://localhost:5555");
$array = array(
    'category' => 'user_signed_up'
);
$socket->send(json_encode($array));

Фрагмент из JavaScript

// Connect to the website
var connection = new ab.Session('ws://MY_IP_ADDRESS:8080',
    function(){
        console.log('Connected to WebSocket');
        connection.subscribe('user_signed_up',function(topic,data){
            console.log(topic,data);
        });
    },
    function(){
        console.log('WebSocket Connection Closed');
    },
    {
        'skipSubprotocolCheck': true
    }
);

Мои вопросы

Все вышеперечисленное работает, но прежде чем приступить к тщательному тестированию и производству, у меня есть пара вопросов:

  1. Это $persistent_id необходимо с getSocket метод? Я прочитал документацию, но для чего она используется? Нужно ли мне это, или я должен использовать это?
  2. Я не смог найти документацию по on метод для класса ZMQ\Context, не рекомендуется ли это? Должен ли я использовать это или вместо этого я должен использовать recv?
  3. Как я могу обеспечить мой push-server.php работает все время? Есть ли какой-нибудь инструмент демона, который я могу использовать, чтобы он всегда работал и автоматически запускался, если сервер перезагружался?
  4. Можно ли прикрепить веб-сокет к моему домену вместо моего IP-адреса? Когда я использую свой домен в JavaScript, я получаю 400 Ошибка...

0 ответов

Другие вопросы по тегам