Как мне получить доступ к циклическому циклу с храповым механизмом php и отправке клиента внутри приложения?

У меня есть класс Ratchet и класс приложения chat, который работает нормально. Моя проблема заключается в том, как добавить периодический цикл?

Я попытался следовать примеру в разделе Периодическая отправка сообщений клиентам в Ratchet

Но я никуда не уходил. Моя цель, подобная этому парню, заключается в том, что сервер проверяет, все ли клиенты все еще живы. Каждый раз, когда я пытаюсь использовать addPeriodicTimer, я не могу получить доступ к общедоступной собственности $ clients в chat.php, как парень из приведенной выше ссылки, чтобы отправлять сообщения с таймера в server.php. Цикл foreach в периодическом таймере в server.php продолжает жаловаться, что он, по-видимому, имеет «недопустимый аргумент».

Может ли кто-нибудь увидеть, что я делаю неправильно?

мой код server.php:

<?php require($_SERVER['DOCUMENT_ROOT'].'/var/www/html/vendor/autoload.php'); require_once($_SERVER['DOCUMENT_ROOT']."/var/www/html/bin/chat.php"); use Ratchet\Server\IoServer; use Ratchet\Http\HttpServer; use Ratchet\WebSocket\WsServer; use Ram\Chat; $server = IoServer::factory(new HttpServer(new WsServer(new Chat())), 8080); // Server timer <------ having trouble here $server->loop->addPeriodicTimer(5, function () use ($server) { foreach($server->app->clients as $client) { //$client->send("[helloworld]"); } }); $server->run(); ?> 

и мой chat.php:

 <?php namespace Ram; use Ratchet\MessageComponentInterface; use Ratchet\ConnectionInterface; error_reporting(E_ALL ^ E_NOTICE); session_id($_GET['sessid']); if(!session_id) session_start(); $userid = $_SESSION["userid"]; $username = $_SESSION["username"]; $isadmin = $_SESSION["isadmin"]; $resources = array(); class Users { public $name; public $resid; public $timestamp; } class Chat implements MessageComponentInterface { public $clients; var $users = array(); /* function cmp($a, $b) { return strcmp($a->name, $b->name); } function removeObjectById(ConnectionInterface $id , $arr) { $array = $arr; foreach ( $array as $key => $element ) { if ( $id->resourceId == $element->resid ) { unset($array[$key]); break; } } usort($array, "cmp"); return $array; } */ public function __construct() { $this->clients = new \SplObjectStorage; } public function onOpen(ConnectionInterface $conn) { $this->clients->attach($conn); } public function onClose(ConnectionInterface $conn) { //$users = removeObjectById($conn, $users); $this->clients->detach($conn); } public function onMessage(ConnectionInterface $conn, $msg) { $msgjson = json_decode($msg); $tag = $msgjson->tag; if($tag == "[msgsend]") { foreach($this->clients as $client) { $client->send($msg); } } else if($tag == "[bye]") { foreach($this->clients as $client) { $client->send($msg); } $this->clients->detach($conn); } else if($tag == "[connected]") { //store client information $temp = new Users(); $temp->name = $msgjson->uname; $temp->resid = $conn->resourceId; $temp->timestamp = date('Ymd H:i:s'); $users[] = $temp; //usort($users, "cmp"); //send out messages foreach($this->clients as $client) { $client->send($msg); } } else if($tag == "[imalive]") { //update user timestamp who sent [imalive] if (is_array($users) || is_object($users)) { foreach($users as $user) { if($msgjson->uname == $user->name) { $user->timestamp = date('Ymd H:i:s'); } } } } } public function onError(ConnectionInterface $conn, Exception $e) { echo "Error: " . $e->getMessage(); $conn -> close(); } } ?> с <?php namespace Ram; use Ratchet\MessageComponentInterface; use Ratchet\ConnectionInterface; error_reporting(E_ALL ^ E_NOTICE); session_id($_GET['sessid']); if(!session_id) session_start(); $userid = $_SESSION["userid"]; $username = $_SESSION["username"]; $isadmin = $_SESSION["isadmin"]; $resources = array(); class Users { public $name; public $resid; public $timestamp; } class Chat implements MessageComponentInterface { public $clients; var $users = array(); /* function cmp($a, $b) { return strcmp($a->name, $b->name); } function removeObjectById(ConnectionInterface $id , $arr) { $array = $arr; foreach ( $array as $key => $element ) { if ( $id->resourceId == $element->resid ) { unset($array[$key]); break; } } usort($array, "cmp"); return $array; } */ public function __construct() { $this->clients = new \SplObjectStorage; } public function onOpen(ConnectionInterface $conn) { $this->clients->attach($conn); } public function onClose(ConnectionInterface $conn) { //$users = removeObjectById($conn, $users); $this->clients->detach($conn); } public function onMessage(ConnectionInterface $conn, $msg) { $msgjson = json_decode($msg); $tag = $msgjson->tag; if($tag == "[msgsend]") { foreach($this->clients as $client) { $client->send($msg); } } else if($tag == "[bye]") { foreach($this->clients as $client) { $client->send($msg); } $this->clients->detach($conn); } else if($tag == "[connected]") { //store client information $temp = new Users(); $temp->name = $msgjson->uname; $temp->resid = $conn->resourceId; $temp->timestamp = date('Ymd H:i:s'); $users[] = $temp; //usort($users, "cmp"); //send out messages foreach($this->clients as $client) { $client->send($msg); } } else if($tag == "[imalive]") { //update user timestamp who sent [imalive] if (is_array($users) || is_object($users)) { foreach($users as $user) { if($msgjson->uname == $user->name) { $user->timestamp = date('Ymd H:i:s'); } } } } } public function onError(ConnectionInterface $conn, Exception $e) { echo "Error: " . $e->getMessage(); $conn -> close(); } } ?> 

Почему бы не определить экземпляр объекта Chat перед переходом на HTTPServer :

 $chat = new Chat(); $server = IoServer::factory(new HttpServer(new WsServer($chat)), 8080); // Server timer <------ having trouble here $server->loop->addPeriodicTimer(5, function () use ($chat) { foreach($chat->clients as $client) { //$client->send("[helloworld]"); } }); $server->run();