我有一个连接到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);
});
答案 0 :(得分:0)
这是您面临的一个有趣的问题。有很多要检查的地方-但是,我建议的第一个问题是以下代码:
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);
});
并尝试一下。如果这可行,则您发现了问题。下一步是确保身份验证正常工作-如果没有完整的代码,则很难为此提出建议。如果您的问题仍未解决,请随时编辑问题并共享代码。