sse => ws
This commit is contained in:
34
dist/ws.js
vendored
Normal file
34
dist/ws.js
vendored
Normal file
@@ -0,0 +1,34 @@
|
||||
import { logInfo } from "./logger.js";
|
||||
export class WsService {
|
||||
clients = new Set();
|
||||
listeners = [];
|
||||
onClientChange(callback) {
|
||||
this.listeners.push(callback);
|
||||
return () => {
|
||||
this.listeners = this.listeners.filter((cb) => cb !== callback);
|
||||
};
|
||||
}
|
||||
emitClientChange() {
|
||||
for (const callback of this.listeners) {
|
||||
callback(this.clients.size);
|
||||
}
|
||||
}
|
||||
addClient(ws) {
|
||||
this.clients.add(ws);
|
||||
logInfo(`Socket connected. Total clients: ${this.clients.size}`);
|
||||
this.emitClientChange();
|
||||
}
|
||||
removeClient(ws) {
|
||||
this.clients.delete(ws);
|
||||
logInfo(`Socket disconnected. Total clients: ${this.clients.size}`);
|
||||
this.emitClientChange();
|
||||
}
|
||||
broadcast(message) {
|
||||
this.clients.forEach((socket) => {
|
||||
socket.send(JSON.stringify(message));
|
||||
});
|
||||
}
|
||||
getClientCount() {
|
||||
return this.clients.size;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user