我有一个连接到https服务器的socket.io,监听javascript以向其发出信息。我发现当我刷新时,套接字正在记录连接 - 因此,如果我在代码的 on('connection', function(socket) { }
部分中 console.log 某些内容,我将在控制台中看到响应。
我发现,在服务器端,socket.on()
调用没有获取任何内容。
因此,如果我在 Javascript 中有一行 socket.emit('ping', msg)
,则“ping”将在前 9-10 次刷新时在服务器端工作,然后在第 11 次刷新时它将停止工作 - 并且它将停止在所有设备和所有浏览器上工作。因此,如果我打开另一个浏览器并尝试加载它,它也不会工作。
我已经检查过是否存在多个连接建立或类似的情况,但我没有看到任何东西。知道为什么会发生这种奇怪的行为吗?
服务器端
io.use(function(socket, next) {
// Authentication of the user is happening here - checking for cookies, sessions, etc.
}).on('connection', function(socket) {
// Setting up some variables and checking other stuff
var socketID = socket["id"];
var username = socketUsers[socketID];
locked[socketID] = {};
// Checking for the username
if(username == '' || typeof username == "undefined") {
// Emit some stuff back to Javascript
io.to(`${socketID}`).emit('criticalError', true);
return false;
}
else {
// We have a valid login, so connect to the server
++connected;
// This line will console log every time I refresh
console.log("Some text");
socket.on('ping', function(msg) {
// This line will console log for the first 9-10 refreshes, and then it suddenly stops working. Any ideas why?
console.log('Server was pinged by ' + username);
});
// This line will console log every time I refresh
console.log("Some other text");
}
});
客户端
var socket = io('https://example.com:1337');
$(document).ready(function() {
socket.emit('ping', true);
});
最佳答案
这是您面临的一个有趣的问题。有多个点需要检查 - 但是我建议的第一个问题是使用以下代码:
var socket = io('https://example.com:1337');
$(document).ready(function() {
socket.emit('ping', true);
});
如果这是客户端的确切代码,则可能会在连接握手完成之前调用 socket.emit
。这可能是随机的,因为有时文档就绪事件可能会延迟。尝试为发出事件设置超时 -
var socket = io('https://example.com:1337');
$(document).ready(function() {
setTimeout(function(){socket.emit('ping', true);},2000);
});
并尝试一下。如果这有效,那么您就发现了问题。下一步是确保身份验证正常工作 - 如果没有完整的代码,就很难提供建议。如果您的问题未得到解决,请随时编辑问题并共享代码。
关于javascript - 多次刷新后 Socket.io 停止工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57959491/