Spaces:
Sleeping
Sleeping
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}`); | |
} | |
}); | |