socket.emit 抛出超时错误,即使消息已成功发送

问题描述 投票:0回答:1
  socket.on("msg-sent", (msg, hit, receiver) => {
    socket
      .to(SOCKET_ID_DIR[hit]?.[receiver])
      .emit("msg-received", msg, (err, res) => {
        if (err) {
          console.log("msg not received ", err);
        } else {
          console.log("msg received");
        }
      });
  });

我打开了 2 个浏览器。当一个浏览器发送消息时,上面的 socket io 代码片段会将此消息发送到另一个浏览器。

我知道消息已成功发出,因为消息已记录到其他浏览器的控制台。然而,这个

console.log("msg not received ", err)
正在套接字io服务器端打印出来。

msg not received  Error: operation has timed out
    at Timeout._onTimeout (/home/user/Documents/project/socket_22/node_modules/socket.io/dist/broadcast-operator.js:182:17)
    at listOnTimeout (internal/timers.js:557:17)
    at processTimers (internal/timers.js:500:7)

为什么?

node.js reactjs socket.io
1个回答
0
投票

确保您在服务器端进行了以下配置:

var app  = express();
var http = require('http').Server(app);
const io = require('socket.io')(http, {
  cors: {
    origin: '*', //may be secured by using the exact domain name
  }
});
io.on('connect', socket => {
  socket.emit('socketId', socket.id) // send each client their socket id
})
app.set('socketio', io);
© www.soinside.com 2019 - 2024. All rights reserved.