Periodically sending messages to clients in Ratchet

后端 未结 2 1448
广开言路
广开言路 2020-12-20 10:21

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

I will post all of the code here: C

相关标签:
2条回答
  • 2020-12-20 10:40

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

    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

    0 讨论(0)
  • 2020-12-20 10:50

    After some updates the Client Connections are accessible in the MessageHandler

        $port = 3001;
        $handler = new MessageHandler();
    
    
        $server = IoServer::factory(
            new HttpServer(
                new WsServer(
                    handler 
                )
            ),
            $port
        );
        $server->loop->addPeriodicTimer(0.1, function () use ($handler) {
            handler->doStuff();
        });
    
        $server->run();
    

    The MessageHandler can be found here. The doStuff method should be implemented in this class:

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

    0 讨论(0)
提交回复
热议问题