【发布时间】:2021-01-25 07:00:35
【问题描述】:
有一个 symfony 应用程序使用带有 Ratchet 的 php websockets (http://socketo.me/docs/sessions)。创建一个可以将接收到的消息广播到所有连接的客户端(Web 浏览器)的 websocket 应用程序似乎很常见。但是我有一个大问题是只向特定客户端发送消息(例如,使用 getUser() 加载用户并找到其所属的 websocket 客户端对象)。
这是我的设置:
// WebsocketServer.php
$server = IoServer::factory(
new HttpServer(
new SessionProvider(
new WsServer(
new WebSocketCommunicator()
),
new MySessionHandler())
),
$this->_websocketPort
);
$server->run();
// Handler for communication with clients
class WebSocketCommunicator implements HttpServerInterface
{
protected $clients;
public function __construct()
{
$this->clients = new \SplObjectStorage();
}
public function onOpen(ConnectionInterface $conn, RequestInterface $request = null)
{
echo "URI: " . $conn->httpRequest->getUri()->getHost();
echo "KEY: " . $conn->Session->get('key');
// ==> I need somethink like:
$user = $conn->Session->get('user_from_session')->getId();
// Attach new client
$this->clients->attach($conn);
}
public function onMessage(ConnectionInterface $pClient, $msg)
{
$msgObj = json_decode($msg);
echo "WebSocket-Request msg: " . $msg->msg;
}
}
使用 websockets 时,没有常规会话或安全对象,我可以在其中加载登录的用户实体 (->getUser())。如上面链接中所述,可以使用 Symfony2 Session 对象或包含标头和 cookie 数据的 httpRequest 对象。有没有办法在其中一个实例中检索用户对象甚至用户 ID?
我能找到的只是这样的示例和解决方法:
Send user ID from browser to websocket server while opening connection
How do you send data to the server onload using ratchet websockets?
https://medium.com/@nihon_rafy/create-a-websocket-server-with-symfony-and-ratchet-973a59e2df94
现在有解决这个问题的现代解决方案吗?或者我可以阅读的任何类型的教程或参考资料?
【问题讨论】:
标签: php symfony websocket session-cookies ratchet