我正在使用 Ratchet,我喜欢它的实现。我正在尝试使用带有
MessageComponentInterface
的聊天示例类向所有连接的客户端发送消息,但在执行 php 脚本后得到一个 null
对象,并且没有任何内容发送到连接的客户端。
聊天类:
<?php
namespace MyApp;
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 || this is the function I'd like to use to send messages to all clients
# it works fine when clients connect but I'm not able to use it properly in notify.php
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();
}
}
服务器.php:
use MyApp\ChatServer;
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:
use MyApp\ChatServer;
require('./chat.php');
$message = "sending message from registerEvent";
echo $message;
$conn = new ChatServer();
$res = $conn->sendMessageToAll($message);
echo '<br/>';
echo json_encode($res);
当我执行$res
时,
null
是notify.php
。我正在单独测试它,因为我的目标是创建一个函数,以便在数据库表中创建新寄存器时向所有连接的用户发送消息。
我该如何修复它以使其按照我的目标正常工作?我一直在阅读一些有关它的问题,但我仍然无法使其发挥作用。
你的变量
$res
为空,因为你的sendMessageToAll函数没有return
你应该实现一些逻辑并返回它