you can merge the code from my answer about socket.io
https://stackoverflow.com/a/62547135/2068876
with the example given on Github:
https://github.com/websockets/ws#multiple-servers-sharing-a-single-https-server
try something like this (not tested, but it seems valid since the principle is the same):
./pages/api/wss1.js
import { WebSocketServer } from "ws";
const wss1Handler = (req, res) => {
if (!res.socket.server.wss1) {
console.log("*First use, starting wss1");
const wss1 = new WebSocketServer({ noServer: true });
res.socket.server.on("upgrade", function upgrade(request, socket, head) {
wss1.handleUpgrade(request, socket, head, function done(ws) {
wss1.emit('connection', ws, request);
});
});
res.socket.server.wss1 = wss1;
} else {
console.log("wss1 already running");
}
res.end();
}
export const config = {
api: {
bodyParser: false
}
}
export default wss1Handler;