Как сделать блок с пользователями Онлайн в Ratchet чате
Подскажите, пожалуйста, как связать $name подключившегося клиента с его $conn->resourceId? Не понимаю, как иначе организовать блок с никами клиентов, которые находятся в онлайне. Чтобы при подключении появлялся ник в блоке, а при отключении исчезал.
Код на стороне клиента:
<?php
$name = 'alex';
?>
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<title>Chat</title>
</head>
<body>
<input type="text" class="message">
<button>Отправить</button>
<hr>
<div class="panel"></div>
</body>
</html>
<script src="jquery-3.5.1.min.js"></script>
<script>
var conn = new WebSocket('ws://localhost:49118');
var login = "<?=$name?>";
conn.onopen = function () {
console.log("Connection established!");
};
conn.onmessage = function (event) {
console.log(event.data);
$('.panel').append(event.data + '<br>');
};
$('button').on('click', function () {
if ($('.message').val() != '') {
var msg = $('.message').val();
conn.send(login + ': ' + msg);
$('.message').val('');
}
});
</script>
Код на сервере:
<?php
require 'vendor/autoload.php';
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class Chat implements MessageComponentInterface {
protected $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn) {
$this->clients->attach($conn);
echo "Новое подключение! ({**$conn->resourceId**})\n";
}
public function onClose(ConnectionInterface $conn) {
$this->clients->detach($conn);
echo "Connection {$conn->resourceId} has disconnected\n";
}
public function onMessage(ConnectionInterface $from, $msg) {
$numRecv = count($this->clients) - 1;
echo sprintf('Connection44 %d sending message "%s" to %d other connection%s' . "\n"
, $from->resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's');
foreach ($this->clients as $client) {
$client->send($msg);
}
}
public function onError(ConnectionInterface $conn, \Exception $e) {
echo "An error has occurred: {$e->getMessage()}\n";
$conn->close();
}
}
$server = IoServer::factory(
new HttpServer(
new WsServer(
new Chat()
)
),
49118
);
$server->run();