php - Ratchet ,插入集成,不工作

标签 php sockets laravel ratchet

我正在使用 Ratchet 和 Laravel。

这是我的主要套接字服务器:

<?php
/**
 * Created by PhpStorm.
 * User: harshvardhangupta
 * Date: 27/05/16
 * Time: 1:40 PM
 */
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
);

$loop->run();

这是我的套接字 Controller :
<?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);
    }


    public function onUnSubscribe(ConnectionInterface $conn, $topic) {
    }
    public function onOpen(ConnectionInterface $conn) {
        echo"open";

    }
    public function onClose(ConnectionInterface $conn) {
        echo "close";
    }

    /* 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.
    }
}

还有另一个脚本调用:
        $context = new ZMQContext();
        $socket = $context->getSocket(ZMQ::SOCKET_PUSH, 'my pusher');
        $socket->connect("tcp://localhost:5555");
        $socket->send("okay");
        die("okay");

首先我在浏览器中运行客户端代码(注意,它与服务器在同一台机器上):
<script src="http://autobahn.s3.amazonaws.com/js/autobahn.min.js"></script>
<script>
    var conn = new ab.Session('ws://localhost:8080',
        function() {
            conn.subscribe('kittensCategory', function(topic, data) {
                // This is where you would add the new article to the DOM (beyond the scope of this tutorial)
                console.log('New article published to category "' + topic + '" : ' + data.title);
            });
        },
        function() {
            console.warn('WebSocket connection closed');
        },
        {'skipSubprotocolCheck': true}
    );
</script>

此连接有效,因为我可以在服务器控制台输出中看到日志消息。
但是,当我调用应该向客户端发送数据的脚本时,客户端没有收到它。客户端浏览器中不会产生日志消息。

最佳答案

解释为什么您的配置不起作用。

您正在发送消息 "okay"从您拥有的代码片段到推送服务器

 $context = new ZMQContext();
 $socket = $context->getSocket(ZMQ::SOCKET_PUSH, 'my pusher');
 $socket->connect("tcp://localhost:5555");
 $socket->send("okay"); -- HERE --
 die("okay");

在这段代码中,您收到该调用,此方法希望您发送 $entryData['category']作为您要将数据发送到的“ channel ”
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);
}

虽然客户端连接到kittensCategory
conn.subscribe('kittensCategory', function(topic, data){

您实际上应该做的是向 pushserver 发送一个正确的对象,以便 websocket 知道将数据发送到哪里。
$entryData = array(
    'category' => 'kittensCategory',
    'data'    =>  'hello'
);

此代码将发送您的 datakittensCategory
如果您需要更多信息,请告诉我

关于php - Ratchet ,插入集成,不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37481148/

相关文章:

php - 如何更改 "zend_log"中的日期格式

php - AWS RDS : How to access/connect to RDS MySql DB From localhost

c - 使用套接字传输数据时避免结构填充的最佳方法是什么?

php - 没有数据库的 Laravel 中的 JWT 身份验证

javascript - 使用 Parsley JS 添加从服务器返回的错误消息

javascript - 将带有图像的表单上传到ajax和php

php - 简单的操作,Cassandra 比 Mysql 慢很多?

mysql - 获取 "Can' t 通过套接字 '/var/run/mysqld/mysqld.sock' 连接到本地 MySQL 服务器“为 Ruby on Rails 应用程序设置 mysql 数据库时出错

Java - 套接字 - 卡住

php - 运行 Laravel 的 artisan session 时出错 :table with pgSQL