定期向 Ratchet 中的客户端发送消息

Periodically sending messages to clients in Ratchet(定期向 Ratchet 中的客户端发送消息)
本文介绍了定期向 Ratchet 中的客户端发送消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在尝试定期发送hello world!"从 Ratchet 教程向所有连接到聊天服务器的客户端发送消息

I'm trying to periodically send a "hello world!" message to all clients connected to the chat-server from the Ratchet tutorial

我将在这里发布所有代码:聊天.php:

I will post all of the code here: Chat.php:

<?php
namespace MyApp;
use RatchetMessageComponentInterface;
use RatchetConnectionInterface;

class Chat implements MessageComponentInterface {
    public $clients;

    public function __construct() {
        $this->clients = new SplObjectStorage;
            }

    public function onOpen(ConnectionInterface $conn) {
        // Store the new connection to send messages to later
        $this->clients->attach($conn);

        echo "New connection! ({$conn->resourceId})
";
    }

    //this worked but I don't want this behaviour
    public function onMessage(ConnectionInterface $from, $msg) {
        /*$numRecv = count($this->clients) - 1;
        echo sprintf('Connection %d sending message "%s" to %d other connection%s' . "
"
            , $from->resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's');

        foreach ($this->clients as $client) {
            if ($from !== $client) {
                // The sender is not the receiver, send to each client connected
                $client->send($msg);
            }
        }*/
    }

    public function onClose(ConnectionInterface $conn) {
        // The connection is closed, remove it, as we can no longer send it messages
        $this->clients->detach($conn);

        echo "Connection {$conn->resourceId} has disconnected
";
    }

    public function onError(ConnectionInterface $conn, Exception $e) {
        echo "An error has occurred: {$e->getMessage()}
";

        $conn->close();
    }
}

聊天服务器.php:

<?php
use RatchetServerIoServer;
use MyAppChat;

    require dirname(__DIR__) . '/vendor/autoload.php';

    $server = IoServer::factory(
        new Chat(),
        8080
    );

    $server->run();

为了测试我理解了多少文档,我在服务器的循环中添加了一个计时器

To test how much of the docs I understood , I added a timer to the server's loop

    <?php
    use RatchetServerIoServer;
    use MyAppChat;

        require dirname(__DIR__) . '/vendor/autoload.php';

        $server = IoServer::factory(
            new Chat(),
            8080
        );


        // My code here
        $server->loop->addPeriodicTimer(5, function () {
          echo  "custom loop timer working !";        
        });


        $server->run();

并且它在启动服务器后每五秒输出一次该字符串工作正常.

and it worked fine outputting that string every five seconds after starting the server.

现在我尝试这样做,尝试向存储在 MessageComponentInterface 中的客户端发送一条消息,该接口称为教程中的 Chat

Now I tried doing it like so, trying to send a message to clients stored in the MessageComponentInterface called Chat from the tutorial

$server->loop->addPeriodicTimer(5, function () {        
    foreach ($server->app->clients as $client) {                  
            $client->send("hello client");          
    }
});

但我得到 $server->app 为 NULL 这可能是因为我现在在 function() 块中.当谈到面向对象的 PHP 时,我不是专家,这个小项目将肯定对我有很大帮助.如何在计时器内访问名为 app 的服务器的 MessageComponentInterface 属性,然后将数据发送到存储在其中的客户端?

But I'm getting that $server->app is NULL which is probably because I'm now inside the function() block .I'm not an expert when it comes to Object oriented PHP, and this little project will sure help me a lot. How can I access the MessageComponentInterface called app property of the server inside the timer and then send data to the clients stored in there?

推荐答案

$server 没有在函数作用域中定义,父作用域的变量不会被继承到子作用域默认.闭包可以通过使用 use 语言结构从父作用域继承变量.

$server isn't defined in the function scope and variables from the parent scope don't get inherited to the child scope by default. Closures can inherit variables from the parent scope by using the use language construct.

$server->loop->addPeriodicTimer(5, function () use ($server) {        
    foreach ($server->app->clients as $client) {                  
            $client->send("hello client");          
    }
});

关于匿名函数(闭包)的更多信息:https://secure.php.net/manual/en/functions.anonymous.php
有关变量范围的更多信息:https://secure.php.net/manual/en/language.variables.scope.php

More information about anonymous functions (closures): https://secure.php.net/manual/en/functions.anonymous.php
More information about variables scope: https://secure.php.net/manual/en/language.variables.scope.php

这篇关于定期向 Ratchet 中的客户端发送消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

DeepL的翻译效果还是很强大的,如果我们要用php实现DeepL翻译调用,该怎么办呢?以下是代码示例,希望能够帮到需要的朋友。 在这里需要注意,这个DeepL的账户和api申请比较难,不支持中国大陆申请,需要拥有香港或者海外信用卡才行,没账号的话,目前某宝可以
PHP通过phpspreadsheet导入Excel日期,导入系统后,全部变为了4开头的几位数字,这是为什么呢?原因很简单,将Excel的时间设置问文本,我们就能看到该日期本来的数值,上图对应的数值为: 要怎么解决呢?进行数据转换就行,这里可以封装方法,或者用第三方的
mediatemple - can#39;t send email using codeigniter(mediatemple - 无法使用 codeigniter 发送电子邮件)
Laravel Gmail Configuration Error(Laravel Gmail 配置错误)
Problem with using PHPMailer for SMTP(将 PHPMailer 用于 SMTP 的问题)
Issue on how to setup SMTP using PHPMailer in GoDaddy server(关于如何在 GoDaddy 服务器中使用 PHPMailer 设置 SMTP 的问题)