棘轮:onOpen之后会自动显示消息

时间:2019-02-01 17:59:26

标签: php websocket ratchet ws

我想在一个客户端连接到服务器时发送一条自动消息。实际上,我将发送已经在“更新”变量中注册的数据。但是发送OnOpen()方法不起作用。请参阅下面的代码。当我将send操作放入OnOpen()时,连接不再起作用。任何想法 ?没有这条线,没有问题。 Connexion和OnMessage效果很好。 我需要发送第一条消息,而无需客户端采取任何行动。

class Update implements MessageComponentInterface
{
    /**
     * @var SplObjectStorage
     */
    private $clients;

    /**
     * @var ConnectionInterface
     */
    private $socketUpdater;

    /**
     * @var ArrayCollection
     */
    private $updates;

    public function __construct(ContainerInterface $container, int $script_id) {
        $this->clients = new SplObjectStorage;
        $this->updates = [];
    }

    /**
     * When a new connection is opened it will be passed to this method
     * @param  ConnectionInterface $conn The socket/connection that just connected to your application
     * @throws \Exception
     */
    function onOpen(ConnectionInterface $conn)
    {
        echo "New connection!\n";
        $this->clients->attach($conn);
        // THIS LINE BROKE THE CLIENT CONNECTION
        $conn->send(json_encode(['updates' => $this->updates]));

    }

    /**
     * Triggered when a client sends data through the socket
     * @param  \Ratchet\ConnectionInterface $from The socket/connection that sent the message to your application
     * @param  string $msg The message received
     * @return bool
     * @throws \Exception
     */
    function onMessage(ConnectionInterface $from, $msg)
    {
        echo "Message reçu \n";
        $object = json_decode($msg);
        // SAVE UPDATES FOR FUTUR CLIENTS
        $this->updates = $object->updates;
        // SEND UPDATE INFO TO THE CONNECTED CLIENTS
        foreach ($this->clients as $client) {
            $client->send(json_encode(['updates' => $this->updates]));
        }
        return true;
    }
}

0 个答案:

没有答案