With ws, Node.js WebSocket library, it is possible to have multiple servers sharing a single HTTP/S server.
Is it possible to do the same with socket.io?
I need to have two WebSocket servers on the same HTTP server, one for socket.io and another one for Apollo subscriptions. I can set up Apollo subscription server with a Websocket server but not for socket.io, socket.io only accepts HTTP server.
I thought in doing something like this:
const socketioWsS = new WebSocket.Server({ noServer: true });
const graphqlWsS = new WebSocket.Server({ noServer: true });
const io = socketIo(socketioWsS, {
transports: ["websocket"]
});
server.on("upgrade", function upgrade(request, socket, head) {
const pathname = url.parse(request.url).pathname;
if (pathname === "/socket.io/") {
socketioWsS.handleUpgrade(request, socket, head, function done(ws) {
socketioWsS.emit("connection", ws, request);
});
} else if (pathname === "/graphql") {
graphqlWsS.handleUpgrade(request, socket, head, function done(ws) {
graphqlWsS.emit("connection", ws, request);
});
} else {
socket.destroy();
}
});
server.listen(config.app.port, () => {
...
new SubscriptionServer(
{
execute,
subscribe,
schema
},
{
server: graphqlWsS
}
);
});
It works well for Graphql subscriptions, but it does not work for socket.io.