Search code examples
phpnetwork-programmingwebsocketratchet

Ratchet Websocket push integration


I am trying to develop a chat system using Websockets (Ratchet). Until now I have already made a functional PHP based Websocket server that is able to answer on predefined JSON encoded message using the following method.

function onMessage(ConnectionInterface $from, $msg){ ... }

The problem is that I'd like to push messages from the backend database via a background worker/thread to the right client, if something changed in my tables. Is this possible using PHP?

I don't want the client asking the websocket server every 5 minutes to refresh its state as shown below.

{"action":"giveMeUpdates"}

but the webserver should be able to do something like this:

{"status":"newMessages", "messagelist":[...]}

In addition:

class Chat extends ChatActionHandler implements MessageComponentInterface { ... }

this is my class where the ChatActionHandler holds functions for interacting with client requests. With the MessageComponentInterface i can only reply on Socket events like function onOpen(ConnectionInterface $conn). It is runned by the RatchetIO Server:

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

Solution

  • You can attach timer, like cron with

    $this->loop->addPeriodicTimer($timeout, function($timer) {});