Count the number of connections > users online
Hi guys,
I'm new in the world of the websockets and Ratchet.
I need to display, in my front, the number of users connected. For me, it makes senses that this count as to be done when a new connection is open. So...
public function onOpen(ConnectionInterface $conn)
{
// ....
$count = $this->clients->count() + 1;
$conn->countClient = $count;
$data = json_decode($count);
$this->clients->attach($conn);
echo "New connection! ({$conn->resourceId})\n";
}
What I struggle with, is to have this value in my front:
function connect() {
var conn = new WebSocket('ws://localhost:8080?token={{ user.user_id }}');
// OPEN THE CONNECTION
conn.onopen = function (e) {
console.log("Connection established!", );
};
}
Thanks for you help and advices
Looks like you're half way there.
Think about events+actions; what triggers happen and how do you want to react to them.
Server side Event: Client connects Action 1: Increment counter Action 2: Notify all connections of new value
Server side Event: Client disconnects Action 1: Decrement counter Action 2: Notify all connections of new value
Client side Event: Receive new connection count value Action: Update UI
@cboden I understand what you mean, but I'm new in this new websocket world.
So.. Maybe you can correct me and help to fill the gaps ;)
- Server side Event: Client connects
Action 1: Increment counter This is what I did here
public function onOpen(ConnectionInterface $conn)
{
$count = $this->clients->count() + 1;
$conn->countClient = $count;
$this->clients->attach($conn);
echo "New connection! ({$conn->resourceId})\n";
}
Action 2: Notify all connections of new value Maybe by attaching the count value to the $conn ?
$conn->countClient = $count;
$this->clients->attach($conn);
- Server side Event: Client disconnects Action 1: Decrement counter
public function onClose(ConnectionInterface $conn)
{
$count = $conn->countClient;
// The connection is closed, remove from connection list
$this->clients->detach($conn);
echo "Connection {$conn->resourceId} has disconnected\n";
}
Action 2: Notify all connections of new value
One of my gaps
- Client side Event: Receive new connection count value
the bigger gaps for me.
The client side event "linked" to my php function onConnect is:
conn.onopen = function (e) {
console.log("Connection established!", );
};
Thank you so much for your help