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)
为什么?
确保您在服务器端进行了以下配置:
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);