Skip to content

Commit

Permalink
ws heartbeat
Browse files Browse the repository at this point in the history
  • Loading branch information
tonyzzp committed Jun 20, 2024
1 parent 2f39849 commit 886a40c
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
23 changes: 22 additions & 1 deletion client/src/lib/signal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { Buffer } from "buffer"
let ws: WebSocket
let listeners: signal.Listener[] = []
let myInfo: signal.Info
let hbFun: any

export namespace signal {

Expand All @@ -26,13 +27,15 @@ export namespace signal {
console.log("signalServer", url)
ws = new WebSocket(url)
ws.onclose = () => {
stopHeartbeat()
let state = ws.readyState
ws = null
listeners.forEach(l => {
l.onStatusChanged(state)
})
}
ws.onopen = () => {
startHeartbeat()
listeners.forEach(l => {
l.onStatusChanged(ws.readyState)
})
Expand All @@ -48,6 +51,24 @@ export namespace signal {
}
}

function startHeartbeat() {
if (hbFun) {
clearInterval(hbFun)
}
hbFun = setInterval(() => {
if (ws?.readyState == WebSocket.OPEN) {
ws.send(JSON.stringify({ event: "hb" }))
}
}, 5000)
}

function stopHeartbeat() {
if (hbFun) {
clearInterval(hbFun)
hbFun = null
}
}

export function addListener(listener: Listener) {
if (listeners.indexOf(listener) == -1) {
listeners.push(listener)
Expand Down Expand Up @@ -89,4 +110,4 @@ export namespace signal {
}))
}
}
}
}
9 changes: 7 additions & 2 deletions server/main.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as expressns from "express"
import { Server as HttpServer, IncomingMessage, ServerResponse, createServer } from "http"
import * as wsns from "ws"
import path from "path"
import * as wsns from "ws"

interface ClientInfo {
name?: string,
Expand Down Expand Up @@ -58,6 +58,9 @@ const processors: { [event: string]: (ws: wsns.WebSocket, json: any) => void } =
}
broadcastInfos()
},
"hb": (ws, json) => {
ws.send(JSON.stringify({ event: "hb" }))
},
"request-clients": (ws, json) => {
broadcastInfos()
},
Expand Down Expand Up @@ -104,11 +107,13 @@ function initExpress() {

function initHttpServer() {
httpServer = createServer(express)
httpServer.setTimeout(0)
httpServer.keepAliveTimeout = 0
}

function initWss() {
wss = new wsns.WebSocketServer({
server: httpServer
server: httpServer,
})

wss.on("connection", (ws, req) => {
Expand Down

0 comments on commit 886a40c

Please sign in to comment.