我正在尝试定期向从 Ratchet 教程连接到聊天服务器的所有客户端发送"hello world!"消息
我将在这里发布所有代码:聊天.php:
<?php
namespace MyApp;
use RatchetMessageComponentInterface;
use RatchetConnectionInterface;
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 disconnectedn";
}
public function onError(ConnectionInterface $conn, Exception $e) {
echo "An error has occurred: {$e->getMessage()}n";
$conn->close();
}
}
聊天服务器.php:
<?php
use RatchetServerIoServer;
use MyAppChat;
require dirname(__DIR__) . '/vendor/autoload.php';
$server = IoServer::factory(
new Chat(),
8080
);
$server->run();
为了测试我理解了多少文档,我在服务器的循环中添加了一个计时器
<?php
use RatchetServerIoServer;
use MyAppChat;
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();
启动服务器后每五秒输出一次该字符串可以正常工作。
现在我尝试这样做,尝试向存储在教程中名为聊天的消息组件接口中的客户端发送消息
$server->loop->addPeriodicTimer(5, function () {
foreach ($server->app->clients as $client) {
$client->send("hello client");
}
});
但是我得到$server->应用程序是空的,这可能是因为我现在在函数()块内。在面向对象的PHP方面,我不是专家,这个小项目肯定会对我有很大帮助。如何访问计时器内称为app
服务器属性的MessageComponentInterface
,然后将数据发送到存储在其中的客户端?
$server
未在函数作用域中定义,默认情况下,父作用域中的变量不会继承到子作用域。闭包可以使用use
语言构造从父作用域继承变量。
$server->loop->addPeriodicTimer(5, function () use ($server) {
foreach ($server->app->clients as $client) {
$client->send("hello client");
}
});
有关匿名函数(闭包)的详细信息:https://secure.php.net/manual/en/functions.anonymous.php
有关变量范围的详细信息:https://secure.php.net/manual/en/language.variables.scope.php
经过一些更新后,可以在消息处理程序中访问客户端连接
$port = 3001;
$handler = new MessageHandler();
$server = IoServer::factory(
new HttpServer(
new WsServer(
handler
)
),
$port
);
$server->loop->addPeriodicTimer(0.1, function () use ($handler) {
handler->doStuff();
});
$server->run();
消息处理程序可以在这里找到。doStuff 方法应该在此类中实现:
https://github.com/leorojas22/symfony-websockets/blob/master/src/Websocket/MessageHandler.php