Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Object null when trying to send message #1070

Open
madsongr opened this issue Jul 22, 2024 · 0 comments
Open

Object null when trying to send message #1070

madsongr opened this issue Jul 22, 2024 · 0 comments

Comments

@madsongr
Copy link

madsongr commented Jul 22, 2024

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant