There is a symfony application that uses php websockets with Ratchet (http://socketo.me/docs/sessions). It seems to be very common to create a websocket application that can broadcast a received messages to all connected clients (web browsers). But I have big issues to send a message only to a specific client (e.g. load user with getUser() and find its belonging websocket client object).
This is my setup:
// 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;
}
}
When using websockets there is no regular session or security object where I can load the logged in user entity (->getUser()). As described in the link above there is the possibility to use the Symfony2 Session object or the httpRequest object that contains header and cookie data. Is there a way to retrieve the user object or even the user id in on of there instances?
All I could find are examples and workarounds like these:
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
Is there a modern solution to this now? Or any kind of a tutorial or reference where I could read about?