front-end
This commit is contained in:
63
src/WebsocketManager.js
Normal file
63
src/WebsocketManager.js
Normal file
@@ -0,0 +1,63 @@
|
||||
import { createNodeWebSocket } from '@hono/node-ws'
|
||||
import {serve} from "@hono/node-server";
|
||||
|
||||
export default class WebsocketManager {
|
||||
|
||||
constructor() {
|
||||
this.clients = [];
|
||||
this.lastPing = {};
|
||||
|
||||
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);
|
||||
ws.send(JSON.stringify("cau"));
|
||||
},
|
||||
onMessage(event, ws) {
|
||||
console.log(`Message from client: ${event.data}`)
|
||||
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);
|
||||
},
|
||||
onClose: (event, ws) => {
|
||||
this.leaveClient(ws);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
handleMessage(ws, data) {
|
||||
|
||||
}
|
||||
|
||||
broadcast(message) {
|
||||
this.clients.forEach(client => client.send(JSON.stringify({data: message})));
|
||||
}
|
||||
|
||||
joinClient(ws) {
|
||||
this.clients.push(ws);
|
||||
this.lastPing[ws] = Date.now();
|
||||
}
|
||||
|
||||
leaveClient(ws) {
|
||||
this.clients = this.clients.filter(s => s !== ws);
|
||||
delete this.lastPing[ws];
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user