Envío periódico de mensajes a clientes en Ratchet
Estoy tratando de enviar periódicamente un "¡Hola mundo!" mensaje para todos los clientes conectados al servidor de chat del tutorial de Ratchet
Publicaré todo el código aquí: Chat.php:
<?php
namespace MyApp;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class Chat implements MessageComponentInterface {
public $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn) {
// Store the new connection to send messages to later
$this->clients->attach($conn);
echo "New connection! ({$conn->resourceId})\n";
}
//this worked but I don't want this behaviour
public function onMessage(ConnectionInterface $from, $msg) {
/*$numRecv = count($this->clients) - 1;
echo sprintf('Connection %d sending message "%s" to %d other connection%s' . "\n"
, $from->resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's');
foreach ($this->clients as $client) {
if ($from !== $client) {
// The sender is not the receiver, send to each client connected
$client->send($msg);
}
}*/
}
public function onClose(ConnectionInterface $conn) {
// The connection is closed, remove it, as we can no longer send it messages
$this->clients->detach($conn);
echo "Connection {$conn->resourceId} has disconnected\n";
}
public function onError(ConnectionInterface $conn, \Exception $e) {
echo "An error has occurred: {$e->getMessage()}\n";
$conn->close();
}
}
chat-server.php:
<?php
use Ratchet\Server\IoServer;
use MyApp\Chat;
require dirname(__DIR__) . '/vendor/autoload.php';
$server = IoServer::factory(
new Chat(),
8080
);
$server->run();
Para probar la cantidad de documentos que entendí, agregué un temporizador al bucle del servidor
<?php
use Ratchet\Server\IoServer;
use MyApp\Chat;
require dirname(__DIR__) . '/vendor/autoload.php';
$server = IoServer::factory(
new Chat(),
8080
);
// My code here
$server->loop->addPeriodicTimer(5, function () {
echo "custom loop timer working !";
});
$server->run();
y funcionó bien generando esa cadena cada cinco segundos después de iniciar el servidor.
Ahora intenté hacerlo así, intentando enviar un mensaje a los clientes almacenados en el MessageComponentInterface llamado Chat desde el tutorial
$server->loop->addPeriodicTimer(5, function () {
foreach ($server->app->clients as $client) {
$client->send("hello client");
}
});
Pero estoy obteniendo que $ server-> app es NULL, lo que probablemente se deba a que ahora estoy dentro del bloque function () .No soy un experto en lo que respecta a PHP orientado a objetos, y este pequeño proyecto seguramente me ayudará mucho. ¿Cómo puedo acceder aMessageComponentInterface
llamadoapp
propiedad del servidor dentro del temporizador y luego enviar datos a los clientes almacenados allí?