Search code examples
phpratchetreactphp

Calling a (Ratchet) WampServer method through a React Timer


I am setting up a WampServer with Ratchet. Is it possible to add to the loop a timer that calls a WampServer's method every 30 second?

I have tried the following code:

public function addMonitoringTimer(){

    $this->loop->addPeriodicTimer(30, function() {
        ...
        $this->wampServer->methodName();
        ...
    });

} 

but no timers seems to work.

Note: As this code is a class method, $this is a reference to the class object that has references to the WampServer ($this->wampserver) and the loop used by the WampServer ($this->loop). The method I am calling is not part of the WampServerInterface.


Solution

  • Let's say Pusher is the clas that implements the WampServerInterface. We define a custom (not part of the interface) method onMessageToPush() in Pusher.

    class Pusher implements WampServerInterface {
        ...
        public function onMessageToPush(){
            ...
        }
        ...
    }
    

    Now, create a React loop:

    $loop  = \React\EventLoop\Factory::create();
    

    , we setup a websocket server object:

    $webSock = new \React\Socket\Server($loop);
    $webSock->listen($bindPort, $bindIp);
    

    , we create the WampServer object:

    $pusher = new Pusher();
    $wampServer = new \Ratchet\Wamp\WampServer(
        $pusher
    );
    

    we setup an I/O server using the above wamp server, web socket and loop:

    $ioserver = new \Ratchet\Server\IoServer(
          new \Ratchet\Http\HttpServer(
            new \Ratchet\WebSocket\WsServer(
                    $wampServer
                )
          ),
          $webSock,
        $loop
    );
    

    and now we can define a timer that will call our custom method:

    $loop->addPeriodicTimer(30, function() use ($pusher) {
            $message = "my message";
            $pusher->onMessageToPush($message);
    });
    

    For everyone that may be interested in this, I have built an example that illustrates how to implement some functionality with Ratchet, including the above functionality You can find it here:

    Example of using Ratchet