I'm using Ratchet PHP to send messages to clients, and I'm using
$server->loop->addPeriodicTimer(1, function () use ($row, $server) {...
To send a message every second. I can echo
the message and the MySQL query works, but I am unable to actually access the clients
object in $server
, I can get to $server->app
, but then when I do ->clients
after that, it tells me that $clients
doesn't exist.
To clarify, this isn't a problem when I don't use new HttpServer(...)
but, without it, the browser console says the websocket handshake isn't valid, so that isn't a good workaround.
I've used print_r($server)
and have confirmed that the clients
object is inside a _httpServer:protected
item. If I can access this, I'd be able to send messages, I think.
The code for the actual server video-server.php
:
<?php
include "../../include/db.info.php";
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use React\EventLoop\Factory;
use MyApp\Chat;
require dirname(__DIR__) . '/vendor/autoload.php';
$server = IoServer::factory(
new HttpServer(
new WsServer(
new Chat()
)
), 888
);
$pdo = new PDO("mysql:host=localhost;port=3306;dbname=erewhon", "root", "");
$getUsername = $pdo->prepare("SELECT * FROM messages WHERE id=201");
$getUsername->execute();
$row = $getUsername->fetch(PDO::FETCH_ASSOC);
$server->loop->addPeriodicTimer(1, function () use ($row, $server) {
/*foreach ($server->app->component->clients as $client) {
$client->send("hello client");
}*/
print_r($server->app);
});
$server->run();
?>
The code for the classes file, chat.php
:
<?php
namespace MyApp;
header("Content-Type: application/json; charset=UTF-8");
//include "../../db.info.php";
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class Chat implements MessageComponentInterface {
public $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
echo "Congratulations! the server is now running
";
}
public function onOpen(ConnectionInterface $conn) {
// Store the new connection to send messages to later
$this->clients->attach($conn);
echo "New connection! ({$conn->resourceId})
";
}
public function onMessage(ConnectionInterface $from, $msg) {
//dont need this
}
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
";
}
public function onError(ConnectionInterface $conn, \Exception $e) {
echo "An error has occurred: {$e->getMessage()}
";
$conn->close();
}
}
?>