Open
Description
I'm using Ratchet and I like its implementation. I'm trying to send a message to all clients connected using chat example class with MessageComponentInterface
but I get a null object after executing php script.
chat class:
<?php
use Ratchet\ConnectionInterface;
use Ratchet\MessageComponentInterface;
use Ratchet\Server\IoServer;
require('../vendor/autoload.php');
class ChatServer implements MessageComponentInterface
{
protected $clients;
public function __construct()
{
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn)
{
$this->clients->attach($conn);
$msg = "Connection established!\n";
// send server log to shell
echo $msg;
$this->sendMessageToAll($msg);
}
public function onMessage(ConnectionInterface $from, $msg)
{
foreach ($this->clients as $client) {
// if ($from != $client) {
$client->send($msg);
// }
}
}
# new
public function sendMessageToAll($msg)
{
foreach ($this->clients as $client) {
echo "Sending message to {$client->resourceId} \n";
$client->send($msg);
}
}
# /new
public function onClose(ConnectionInterface $conn)
{
$this->clients->detach($conn);
}
public function onError(ConnectionInterface $conn, Exception $e)
{
$conn->close();
}
}
server.php
require('../vendor/autoload.php');
require('./chat.php');
$app = new Ratchet\App('localhost', 8080);
$app->route('/chat', new ChatServer, array('*'));
$app->route('/echo', new Ratchet\Server\EchoServer, array('*'));
$app->run();
notify.php
require('./chat.php');
$message = "sending message from registerEvent";
echo $message;
$conn = new ChatServer();
$res = $conn->sendMessageToAll($message);
echo '<br/>';
echo json_encode($res);
$res
is null
when I execute notify.php
. I'm testing it separately because my goal is to send a message to all users connected when a new register is created in a database table.
Can you tell me how can I fix it to make it works properly according to my goal?
Metadata
Assignees
Labels
No labels