Search code examples
phpratchet

Closing a Ratchet IOServer


Is there a method of terminating IOServer's loop?

I'm using WebSockets as a hacky inter-app communication system (believe me, if I could use anything else, I would), but I can't break out of the loop and continue my application after calling run() on IOServer.

Do I need to subclass IOServer into TerminatableIOServer or does this feature already exist?


Solution

  • Call stop() on the IOServer's loop.

    Launcher.php

    namespace MyApp;
    
    use Ratchet\Server\IoServer;
    use Ratchet\Http\HttpServer;
    use MyApp\Server;
    
    $server = IoServer::factory(
        new HttpServer(
            new WsServer(
                new Server('stopCallback')
            )
        ),
        $this->port()
    );
    
    $server->run();
    
    echo "if the server ever determines it should close, this will be printed.";
    
    
    // when loop completed, run this function
    function stopCallback() {
        $server->loop->stop();
    }
    

    Server.php

    namespace MyApp;
    
    use Ratchet\MessageComponentInterface;
    use Ratchet\ConnectionInterface;
    
    class Server implements MessageComponentInterface {
        protected $callback;
    
        public function __construct($callback) {
            $this->callback = $callback;
        }
    
        // custom function called elsewhere in this class whenever you want to close the server.
        protected function close() {
            call_user_func($this->callback);
        }
    }