当我的websocket服务器处理连接时,我正在使用线程来运行异步任务。该线程通过套接字连接到另一个打开的服务器。
当客户端连接到Websocket时,套接字调用此类中的一个函数,该函数向所有连接的客户端发送消息。 当线程检索消息时,它将调用相同的函数。
我的问题是,当线程调用此函数时,websocket不会向所有连接的客户端发送消息。即使我在类的实例上调用该函数,所有客户端保存到的变量在两个函数调用中也不同。
我曾经尝试将clients变量作为参数添加到函数中,并使用getters和setters并将其公开。一切都得到相同的结果。
<?php
set_time_limit(0);
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
require_once 'vendor/autoload.php';
class WorkerThread extends Thread {
private $connection;
public $msgHistory;
public function __construct($connection) {
$this->connection = $connection;
$this->msgHistory = array();
}
public function run() {
while (true) {
// Socket reader would be here
$msg = "test";
// Add to message history
$this->msgHistory[count($this->msgHistory)] = $msg;
// Send message to all clients
$this->connection->sendMessageToAllClients(array($msg), false); // Function displays "Connection count: 0"
}
}
}
}
class WebSocketRemoteConsoleHandler implements MessageComponentInterface {
protected $clients;
private $worker;
public function __construct() {
$this->clients = new \SplObjectStorage;
$this->worker = new WorkerThread($this);
$this->worker->start();
}
public function onOpen(ConnectionInterface $conn) {
$this->clients->attach($conn);
$this->sendMessageToAllClients($this->worker->msgHistory, true); // Function displays "Connection count: 1"
}
public function onClose(ConnectionInterface $conn) {
$this->clients->detach($conn);
}
public function onError(ConnectionInterface $conn, \Exception $e) {
$conn->close();
}
public function sendMessageToAllClients($data, $sendMsgHistory) {
echo "Connection count: " . count($this->clients) . PHP_EOL;
foreach($this->clients as $client) {
$client->send(json_encode(array(
"Messages" => $data,
"IsComplete" => $sendMsgHistory
)));
}
}
}
$server = IoServer::factory(
new HttpServer(new WsServer(new WebSocketRemoteConsoleHandler())),
8080
);
$server->run();
?>
当我从类内部调用方法sendMessageToAllClients()
时,它显示Connection count: 1
。当我从websocket类的同一实例中的线程调用函数时,它显示Connection count: 0
。
我期望两个函数调用都应显示已连接1个客户端(Connection count: 1
)。
(我已经启动了webocket,并使用javascript连接了它)