Last active
June 17, 2022 00:53
-
-
Save malikdoksoz/c5fb10efe348c9c595234659a4f1c60a to your computer and use it in GitHub Desktop.
adonisjs 5 websocket
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { WebSocket } from 'ws' | |
import Ws from 'App/Services/Ws' | |
let clientId: number = 0; | |
Ws.boot() | |
const serverIo = Ws.wss; | |
/** | |
* Listen for incoming socket connections | |
*/ | |
interface ExtWebSocket extends WebSocket { | |
isAlive: boolean; | |
} | |
serverIo.on('connection', function connection(ws) { | |
const extWs = ws as ExtWebSocket; | |
clientId++; | |
console.log(clientId + " connected"); | |
extWs.isAlive = true; | |
ws.on('pong', () => extWs.isAlive = true); | |
ws.send('hello'); | |
ws.on('close', function () { | |
console.log(clientId + " disconnected"); | |
}); | |
ws.on('message', function message(data, isBinary) { | |
serverIo.clients.forEach(function each(client) { | |
if (client.readyState === WebSocket.OPEN) { | |
client.send(data, { binary: isBinary }); | |
} | |
}); | |
}); | |
}); | |
const interval = setInterval(function ping() { | |
serverIo.clients.forEach(function each(ws: WebSocket) { | |
const extWs = ws as ExtWebSocket; | |
if (!extWs.isAlive) return ws.terminate(); | |
extWs.isAlive = false; | |
ws.ping(null, undefined); | |
}); | |
}, 5000); | |
serverIo.on('close', function close() { | |
console.log(clientId + " disconnected.."); | |
clearInterval(interval); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Added ping, pong. To avoid automatic shutdown of the connection. Fix isAlive typescript error