Skip to content

Instantly share code, notes, and snippets.

@malikdoksoz
Last active June 17, 2022 00:53
Show Gist options
  • Save malikdoksoz/c5fb10efe348c9c595234659a4f1c60a to your computer and use it in GitHub Desktop.
Save malikdoksoz/c5fb10efe348c9c595234659a4f1c60a to your computer and use it in GitHub Desktop.
adonisjs 5 websocket
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);
});
@malikdoksoz
Copy link
Author

malikdoksoz commented Jun 14, 2022

Added ping, pong. To avoid automatic shutdown of the connection. Fix isAlive typescript error

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment