Spaces:
Sleeping
Sleeping
File size: 1,140 Bytes
940e0ce |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
const uWS = require("uWebSockets.js");
const wss = uWS.App();
const port = process.env.PORT || 7860;
wss
.ws("/problems/:problemId", {
upgrade: (res, req, context) => {
res.upgrade(
{ problemId: req.getParameter(0) },
req.getHeader("sec-websocket-key"),
req.getHeader("sec-websocket-protocol"),
req.getHeader("sec-websocket-extensions"),
context
);
},
open: async (ws) => {
const { problemId } = ws;
ws.subscribe(problemId);
const count = wss.numSubscribers(problemId);
console.log(`[Join] ${problemId} - count: ${count}`);
wss.publish(problemId, `${count}`);
},
close: async (ws) => {
const { problemId } = ws;
const count = wss.numSubscribers(problemId);
console.log(`[Left] ${problemId} - count: ${count}`);
wss.publish(problemId, `${count}`);
},
})
.any("/*", (res, req) => {
res.end("Nothing to see here!");
})
.listen('::', port, (token) => {
if (token) {
console.log(`Listening to port ${port}`);
} else {
console.log(`Failed to listen to port ${port}`);
}
});
|