我有一个连接到https服务器的socket.io,侦听javascript向它发出信息。我发现当我刷新时,套接字正在记录连接,所以如果我在代码的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);
});
发布于 2019-09-16 18:12:24
这是你面临的一个有趣的问题。有多个点需要检查--不过,我建议的第一个问题是下面的代码:
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);
});
试一试。如果这个可行的话,你就会发现问题所在。下一步是确保身份验证工作正常--如果没有完整的代码,就很难提出建议。如果您的问题没有解决,请随时编辑问题并共享代码。
https://stackoverflow.com/questions/57959491
复制相似问题