棘轮推动集成不适用于Laravel

时间:2016-10-14 03:27:59

标签: php zeromq ratchet

我已成功将Ratchet聊天整合到我的Laravel应用程序中,现在我想整合Ratchet推送集成,但遗憾的是没有工作。首先,我在Laravel应用程序项目文件夹的根目录中有 pusher.php 服务器文件

<?php

use App\Http\Controllers\SocketController;

require './vendor/autoload.php';
$loop   = React\EventLoop\Factory::create();
$pusher = new SocketController();

// Listen for the web server to make a ZeroMQ push after an ajax request
$context = new React\ZMQ\Context($loop);
$pull = $context->getSocket(ZMQ::SOCKET_PULL);
$pull->bind('tcp://127.0.0.1:5555'); // Binding to 127.0.0.1 means the only client that can connect is itself
$pull->on('message', array($pusher, 'onBlogEntry'));

// Set up our WebSocket server for clients wanting real-time updates
$webSock = new React\Socket\Server($loop);
$webSock->listen(8080, '0.0.0.0'); // Binding to 0.0.0.0 means remotes can connect
$webServer = new Ratchet\Server\IoServer(
    new Ratchet\Http\HttpServer(
        new Ratchet\WebSocket\WsServer(
            new Ratchet\Wamp\WampServer(
                $pusher
            )
        )
    ),
    $webSock
);

echo "Pusher server is running\n";

$loop->run();

此控制器名为 SocketController.php

<?php
namespace App\Http\Controllers;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Ratchet\Wamp\Topic;
use Ratchet\Wamp\WampServerInterface;

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

    public function onSubscribe(ConnectionInterface $conn, $topic) {
        echo"on";
        $this->subscribedTopics[$topic->getId()] = $topic;
    }

    /**
     * @param string JSON'ified string we'll receive from ZeroMQ
     */
    public function onBlogEntry($entry) {
        $entryData = json_decode($entry, true);

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

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

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

        echo "A new topic has been push";
    }


    public function onUnSubscribe(ConnectionInterface $conn, $topic) {
        echo "A client has subscribed ".$conn->resourceId."\n";
    }


    public function onOpen(ConnectionInterface $conn) {
        echo "A client is connected ".$conn->resourceId."\n";

    }
    public function onClose(ConnectionInterface $conn) {
        echo "A client has been disconnected ".$conn->resourceId."\n";
    }

    /* The rest of our methods were as they were, omitted from docs to save space */
    /**
     * If there is an error with one of the sockets, or somewhere in the application where an Exception is thrown,
     * the Exception is sent back down the stack, handled by the Server and bubbled back up the application through this method
     * @param  ConnectionInterface $conn
     * @param  \Exception $e
     * @throws \Exception
     */
    function onError(ConnectionInterface $conn, \Exception $e)
    {
        // TODO: Implement onError() method.
    }

    /**
     * An RPC call has been received
     * @param \Ratchet\ConnectionInterface $conn
     * @param string $id The unique ID of the RPC, required to respond to
     * @param string|Topic $topic The topic to execute the call against
     * @param array $params Call parameters received from the client
     */
    function onCall(ConnectionInterface $conn, $id, $topic, array $params)
    {
        // TODO: Implement onCall() method.
    }

    /**
     * A client is attempting to publish content to a subscribed connections on a URI
     * @param \Ratchet\ConnectionInterface $conn
     * @param string|Topic $topic The topic the user has attempted to publish to
     * @param string $event Payload of the publish
     * @param array $exclude A list of session IDs the message should be excluded from (blacklist)
     * @param array $eligible A list of session Ids the message should be send to (whitelist)
     */
    function onPublish(ConnectionInterface $conn, $topic, $event, array $exclude, array $eligible)
    {
        // TODO: Implement onPublish() method.
    }
}

是的,我跟踪了http://socketo.me/docs/push的所有内容。接下来,我设置了一个路由和一个用于推送条目的测试控制器。

在路线

Route::get('/test','testController@index');

测试控制器

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;

use \ZMQContext;
use \ZMQ;

class testController extends Controller
{

    public function index(){
         $entryData = array(
            'category' => 'cat',
            'title'    => 'title 1',
            'article'  => 'article 1',
            'when'     => time()
        );


        // This is our new stuff
        $context = new ZMQContext();
        $socket = $context->getSocket(ZMQ::SOCKET_PUSH, 'my pusher');
        $socket->connect("tcp://localhost:5555");

        $socket->send(json_encode($entryData));

       dd($entryData);
    }
}

在客户端,我将它连接到Ratchet推送服务器。

<script src="http://autobahn.s3.amazonaws.com/js/autobahn.min.js"></script>
<script>
    var conn = new ab.Session('ws://localhost:8080',
        function() {
            conn.subscribe('cat', function(topic, data) {
                // This is where you would add the new article to the DOM (beyond the scope of this tutorial)
                alert('New article published to category "' + topic + '" : ' + data.title);
            });
        },
        function() {
            console.warn('WebSocket connection closed');
        },
        {'skipSubprotocolCheck': true}
    );
</script>

现在,我按

运行 pusher.php
  

cd c:/ wamp / www / laravelApp php pusher.php

并且在控制台中,我记录了客户端已连接但当我从浏览器访问 localhost:8000 / test 时(推入条目),它没有

  回声“一个新话题已被推动”;

因为我应该在这里设置

public function onBlogEntry($entry) {
        $entryData = json_decode($entry, true);

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

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

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

        echo "A new topic has been push";
    }

所以这意味着,订阅某个类别不起作用,任何想法,请帮忙吗?

0 个答案:

没有答案