74 lines
1.7 KiB
JavaScript
74 lines
1.7 KiB
JavaScript
import { createNodeWebSocket } from '@hono/node-ws'
|
|
import {serve} from "@hono/node-server";
|
|
|
|
export default class WebsocketManager {
|
|
|
|
constructor() {
|
|
this.clients = [];
|
|
this.lastPing = {};
|
|
this.initData = null;
|
|
|
|
setInterval(() => {
|
|
const thr = Date.now() - 60000;
|
|
this.clients.filter(client => this.lastPing[client] < thr).forEach((client) => this.leaveClient(client));
|
|
}, 10000);
|
|
}
|
|
|
|
getHandler() {
|
|
const _this = this;
|
|
return {
|
|
onOpen: (event, ws) => {
|
|
this.joinClient(ws);
|
|
},
|
|
onMessage(event, ws) {
|
|
if (!event.data)
|
|
return;
|
|
|
|
const data = JSON.parse(event.data);
|
|
if (!data)
|
|
return;
|
|
|
|
if (data.ping) {
|
|
_this.lastPing[ws] = Date.now();
|
|
}
|
|
|
|
if (data.data) {
|
|
_this.handleMessage(ws, data.data);
|
|
console.log(`Data from client: ${event.data}`);
|
|
}
|
|
},
|
|
onClose: (event, ws) => {
|
|
this.leaveClient(ws);
|
|
},
|
|
};
|
|
}
|
|
|
|
handleMessage(ws, data) {
|
|
|
|
}
|
|
|
|
send(ws, data) {
|
|
ws.send(JSON.stringify({data: data}));
|
|
}
|
|
|
|
broadcast(data) {
|
|
this.clients.forEach(client => this.send(client, data));
|
|
}
|
|
|
|
joinClient(ws) {
|
|
this.clients.push(ws);
|
|
this.lastPing[ws] = Date.now();
|
|
this.send(ws, this.initData)
|
|
}
|
|
|
|
leaveClient(ws) {
|
|
this.clients = this.clients.filter(s => s !== ws);
|
|
delete this.lastPing[ws];
|
|
}
|
|
|
|
setInitData(initData) {
|
|
this.initData = initData;
|
|
}
|
|
|
|
}
|