在我的项目中,我想自动向某些客户端发送数据,而不接收来自客户端的任何请求。但是我无法从MessageComponentInterface
类对象的外部访问客户端。我更愿意告诉MessageComponentInterface
班级;向活着的客户发送消息。所以我需要从服务器端触发onMessage功能,我该怎么办呢?
这是我的WebSocketCon类:
<?php
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class WebSocketCon implements MessageComponentInterface {
protected $clients;
public $users;
public function __construct() {
$this->clients = new \SplObjectStorage;
$this->users = [];
}
public function onOpen(ConnectionInterface $conn) {
$this->clients->attach($conn);
echo "New connection! ({$conn->resourceId})\n";
}
public function onMessage(ConnectionInterface $from, $msg) {
$data = json_decode($msg);
if($data->command=="subscribe"){
$this->users[(int)$data->uid] = $from;
echo "New subscribe! ({$data->uid})\n";
}
}
public function sendMessageToAll($msg){
foreach ($this->clients as $client) {
if ($from !== $client) {
$client->send($msg);
}
}
}
public function sendMessageTo($idusers,$msg){
foreach ($idusers as $idu) {
$idu = (int) $idu;
if(array_key_exists($idu,$this->users)){
$this->users[$idu]->send($msg);
}
}
}
public function onClose(ConnectionInterface $conn) {
$this->clients->detach($conn);
if (($key = array_search($conn, $this->users)) !== false) {
unset($this->users[$key]);
}
echo "Connection {$conn->resourceId} has disconnected\n";
}
public function onError(ConnectionInterface $conn, \Exception $e) {
echo "An error has occurred: {$e->getMessage()}\n";
$conn->close();
}
}
这是我的cmd.php:
<?php
require 'vendor/autoload.php';
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
require 'classes/WebSocketCon.php';
$server = IoServer::factory(
new HttpServer(
new WsServer(
new WebSocketCon()
)
),
8081
);
$server->run();
?>