最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

node.js - Socket.io with pm2 cluster mode - Stack Overflow

programmeradmin6浏览0评论

I am running a node app via pm2 using cluster mode (-i 4) and this same node app uses socket.io and since running in cluster mode, I have been not been able to connect to the socket.

I have followed this tutorial to use @socket.io/pm2 instead of pm2 and my code still behaves the same before and after. I have also tried setting transports to only websocket in my client connection and this does connect, but distributes connections throughout the cluster which is not what is intended.

For some reference, here is the code I am working with:

//Some server code:
import { Server } from "socket.io";
import { createAdapter } from "@socket.io/cluster-adapter";
import { setupWorker } from "@socket.io/sticky";

const setupSocketServer = (httpServer) => {
    const io = new Server(httpServer, { cors: { origin: "*" } });
    io.adapter(createAdapter());
    setupWorker(io);

    io.on("connection", async (socket) => {
    
    }
}
//Some client code
import { io, Socket } from "socket.io-client";
socketRef.current = io(";);
setSocket(socketRef.current);

Additionally, I am using Caddy as a reverse proxy. The existing caddy config worked before I ran as a cluster and also when I run with websocket as the only client transport.

website {
    redir {uri} permanent
}

www.website {
    encode zstd gzip
    reverse_proxy /api* localhost:3000
    reverse_proxy /socket.io* localhost:3000
    reverse_proxy /* localhost:8080
}

Any help is greatly appreciated, I cannot seem to figure this out. If more context is needed, don't hesitate to ask!

发布评论

评论列表(0)

  1. 暂无评论