phpwhile-loopratchet

PHP/Ratchet websocket - issues with while loop


I have a very simple websocket using PHP and Ratchet libraray.

When a user opens a specific page it sends the users id to my socket and it should update the status for that user (at the moment I'm just logging it in the console), like this:

<input type="hidden" value="'.$account_id.'" id="account_id">
<input type="hidden" value="trial" id="request_type">
<script>
$(document).ready(function(){
    var conn = new WebSocket('ws://127.0.0.1:8080');

    conn.onopen = function(e){
        console.log("Connection Opened!");
        var account_id = $("#account_id").val();
        var request_type = $("#request_type").val();
        var data = {account_id: account_id, request_type: request_type};
        conn.send(JSON.stringify(data));
    }
    conn.onclose = function(e){
        console.log("Connection Closed!");
    }
    conn.onmessage = function(e) {
        var data = JSON.parse(e.data);
        console.log(data);
    };
    conn.onerror = function(e){
        var data = JSON.parse(e.data);
        console.log(data);
    }
})
</script>

Then my socket script is as follows:

set_time_limit(0);

use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
require dirname(__DIR__) . '../vendor/autoload.php';

class socket implements MessageComponentInterface{
    protected $clients;

    public function __construct(){
        $this->clients = new \SplObjectStorage;
        echo 'Server Started.'.PHP_EOL;
    }

    public function onOpen(ConnectionInterface $socket){
        $this->clients->attach($socket);
        echo 'New connection '.$socket->resourceId.'!'.PHP_EOL;
    }
    public function onClose(ConnectionInterface $socket) {
        $this->clients->detach($socket);
        echo 'Connection '.$socket->resourceId.' has disconnected'.PHP_EOL;
    }
    public function onError(ConnectionInterface $socket, \Exception $e) {
        echo 'An error has occurred: '.$e->getMessage().'!'.PHP_EOL;
        $socket->close();
    }
    public function onMessage(ConnectionInterface $from, $json){
        echo 'Connection '.$from->resourceId.' sent '.$json.PHP_EOL;
        $data = json_decode($json, true);
        $account_id = $data['account_id'];
        $request_type = $data['request_type'];

        try {
            $conn = new PDO("mysql:host=".$db_host.";port:".$db_port.";dbname=".$db_name."", $db_user, $db_pass);
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }catch(PDOException $e){
            echo $e->getMessage();
        }
        
        foreach ($this->clients as $client) {
            if ($from->resourceId == $client->resourceId) {
                if($request_type == 'trial'){
                    // while(true){
                        $response_array= [];
                        $stmt = $conn->prepare("SELECT * FROM table WHERE account_id=:account_id AND last_status_change=now()");
                        $stmt->bindParam(':account_id', $account_id);
                        $stmt->execute();
                        $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
                        foreach($stmt->fetchAll() as $key=>$value) {
                            $response_array[$key] = $value;
                        }
                        if(!empty($response_array)){
                            foreach($response_array as $item){
                                $status = $item['status'];
                            }
                            $response = array(
                                'account_id' => $account_id,
                                'status' => $status
                            );
                            var_dump($response);
                            $client->send(json_encode($response));
                        }
                        // sleep(5);
                    // }
                }
            }
        }
    }
}

$server = IoServer::factory(
    new HttpServer(
        new WsServer(
            new socket()
        )
    ),
    8080
);
$server->run();

As it stands it works as expected, but only gives the current status if the status changed at the time when the page was loaded and I will see the status in the console, as soon as I un-comment the while() loop to actually keep checking the status for updates, my socket will do the var_dump() of the result in the command line when there is a status change but nothing gets logged in the client.

I'm new to websockets, I had been doing long polling by having an interval in JS that was sending a fetch() to a PHP script that got the latest DB results but it wasn't very efficient and was causing issues when a large number of clients were active and constantly making requests to the file which was in turn slowing down the DB. So I'm not sure why the while() loop is affecting it like this or if I am even going about this the right way.


Solution

  • A while loop is not how it works. It will block stuff and infinitely and unnecessarily consume resources.

    What you want is addPeriodicTimer().

    Check periodically for clients that need updates.

    Add to your bootstrapping something like this:

    $reactEventLoop->addPeriodicTimer(5, function() use $messageHandler, $server {
        // Fetch all changed clients at once and update their status
        $clientsToUpdate = getUpdatedClients($server->app->clients);
        foreach ($clientsToUpdate as $client) {
            $client->send(json_encode($response));
        }
    });
    

    This is much more lightweight than any other method, as you can

    1. Fetch N clients status with a single prepared database query
    2. Update only changed clients periodically
    3. Not put your app in a blocking state

    Other resources on Stackoverflow will help you to find the right spot:

    How do I access the ratchet php periodic loop and client sending inside app?

    Periodically sending messages to clients in Ratchet