H
Honoβ€’3mo ago
thai

Websockets connected clients count

Hi, I'd like to know how to get the amount of connected clients.
import { Hono } from 'hono'
import { upgradeWebSocket } from 'hono/cloudflare-workers'
const app = new Hono()
const obj = { data: 5 };

//i'm periodically changing the data in obj
function startTimer() {
return setInterval(() => {
obj.data = Math.random();
}, 1000);
}

const wsApp = app.get(
'/ws',
upgradeWebSocket((c) => {
let timer: NodeJS.Timeout;
return {
onOpen: (event, ws) => {
console.log('connected');
ws.send(JSON.stringify(obj));
timer = startTimer();
},
onClose: (event, ws) => {
//if no clients are connected stop the timer
// if ( ws.clients.size === 0) {
// clearInterval(timer);
// }
}
}
})
)

export type WebSocketApp = typeof wsApp;
import { Hono } from 'hono'
import { upgradeWebSocket } from 'hono/cloudflare-workers'
const app = new Hono()
const obj = { data: 5 };

//i'm periodically changing the data in obj
function startTimer() {
return setInterval(() => {
obj.data = Math.random();
}, 1000);
}

const wsApp = app.get(
'/ws',
upgradeWebSocket((c) => {
let timer: NodeJS.Timeout;
return {
onOpen: (event, ws) => {
console.log('connected');
ws.send(JSON.stringify(obj));
timer = startTimer();
},
onClose: (event, ws) => {
//if no clients are connected stop the timer
// if ( ws.clients.size === 0) {
// clearInterval(timer);
// }
}
}
})
)

export type WebSocketApp = typeof wsApp;
6 Replies
thai
thaiOPβ€’3mo ago
Thank you for anyone's help in advance.
plumbe0
plumbe0β€’3mo ago
I believe you have to track them on your app side, it's not something that the protocol does automatically for you. Maybe use something like redis if your function is executed in serverless environments?
Aditya Mathur
Aditya Mathurβ€’3mo ago
If you were on a server, you could have created a global variable which increments and decrements on onOpen and onClose but for workers you will need to store this value on an external storage solutions like KV or DurableObject
blurSkye πŸ‡΅πŸ‡ΈπŸ‰
unfortunately you will have manually keep track of it
thai
thaiOPβ€’3mo ago
Thank you everyone for your help
blurSkye πŸ‡΅πŸ‡ΈπŸ‰
add solved tag
Want results from more Discord servers?
Add your server