typescript 在www.example.com中socket.io,相同的事件发生2次

3z6pesqy  于 2023-04-07  发布在  TypeScript
关注(0)|答案(2)|浏览(137)

我在socket.io我的项目中使用www.example.com nodejs集群,我不知道为什么同一个事件会发生两次。我尝试了www.example.com的各种版本Socket.io,但我仍然得到一个错误,2个相同的事件可以去。套接字版本:2.0.5

服务器代码

const cluster = require("cluster");
const http = require("http");
const { Server } = require("socket.io");
const redisAdapter = require("socket.io-redis");
const numCPUs = require("os").cpus().length;
const { setupMaster, setupWorker } = require("@socket.io/sticky");

if (cluster.isMaster) {
  console.log(`Master ${process.pid} is running`);

  const httpServer = http.createServer();
  setupMaster(httpServer, {
    loadBalancingMethod: "least-connection", // either "random", "round-robin" or "least-connection"
  });
  httpServer.listen(3000);

  for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  cluster.on("exit", (worker) => {
    console.log(`Worker ${worker.process.pid} died`);
    cluster.fork();
  });
} else {
  console.log(`Worker ${process.pid} started`);

  const httpServer = http.createServer();
  const io = new Server(httpServer);
  io.adapter(redisAdapter({ host: "localhost", port: 6379 }));
  setupWorker(io);

  io.on("connection", (socket) => {
    console.log("connected");
    socket.join("data");
    io.to('data').emit("event", "data");
  });

}

客户编码

const io = require("socket.io-client");

const socket = io.connect("http://localhost:3000");

socket.on("event", (data) => {
  console.log("Received data:", data);
});

bmvo0sr5

bmvo0sr51#

当我将socket.io版本和socket.io客户端降级到旧版本时,它被修复了。

bxgwgixi

bxgwgixi2#

io.to('data').emit("event", "data");

将服务器代码中的该行替换为:

socket.emit("event", "data");

或者:

io.in('data').emit("event", "data");

前一段代码所做的是,一旦创建了服务器并且客户端连接到服务器,它就向客户端发送“event”事件,并且由于客户端已经在侦听“event”事件,因此它将接收两次。

相关问题