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

时间:2016-07-16 16:03:20

标签: php web-services websocket ratchet

我试图定期发送一个'#34; hello world!"从Ratchet教程

连接到聊天服务器的所有客户端的消息

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

<?php
namespace MyApp;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;

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})\n";
    }

    //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' . "\n"
            , $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\n";
    }

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

        $conn->close();
    }
}

聊天server.php:

<?php
use Ratchet\Server\IoServer;
use MyApp\Chat;

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

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

    $server->run();

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

    <?php
    use Ratchet\Server\IoServer;
    use MyApp\Chat;

        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();

并且在启动服务器后每隔五秒输出该字符串就可以了。

现在我尝试这样做,尝试向教程中名为Chat的MessageComponentInterface中存储的客户端发送消息

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

但是我得到$ server-&gt;应用程序是NULL,这可能是因为我现在在function()块中。我在面向对象时不是专家PHP,这个小项目肯定会帮助我很多。 如何访问计时器内服务器的MessageComponentInterface调用app属性,然后将数据发送到存储在那里的客户端?

2 个答案:

答案 0 :(得分:3)

$server未在函数范围内定义,并且父作用域中的变量默认不会继承到子作用域。闭包可以使用use语言构造从父作用域继承变量。

$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

答案 1 :(得分:0)

一些更新后,可以在MessageHandler中访问客户端连接

d=[[1,2,3],[3,5,4],[5,6,9],[0,2,1],[1,2,3]]
s=0
for i in range(len(d)):
   for j in range(i+1,len(d)):
       if d[i]==d[j]:
           s=s+1
           x=i
           y=j
print(s)
print(x,y)

可以在此处找到MessageHandler。 doStuff方法应在此类中实现:

https://github.com/leorojas22/symfony-websockets/blob/master/src/Websocket/MessageHandler.php