Skip to content
Advertisement

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?

Advertisement

Answer

Call stop() on the IOServer‘s loop.

Launcher.php

namespace MyApp;

use RatchetServerIoServer;
use RatchetHttpHttpServer;
use MyAppServer;

$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 RatchetMessageComponentInterface;
use RatchetConnectionInterface;

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);
    }
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement