我一直在努力建立一个在Socket.io中使用房间的基本通知系统。但是,出于某种原因,它只会在您刷新页面时每隔一段时间运行一次。
我已经简化了代码以使其更容易调试,但问题仍然存在。每次刷新页面时,一切似乎都有效,除了加入一个房间(只有一半的时间)。会发生什么事?
编辑:我正在使用Socket.io版本1.1.0和Node.js版本0.10.31 edit2:添加了FunnyLookinHat的建议(但它仍然无法解决问题)
客户端代码:
socket = io.connect('example.com:8081'),
socket.on('connect', function () {
socket.on('startup', function(data) {
console.log(data.message);
});
socket.emit('joinRoom');
});
服务器端代码:
var io = require('socket.io').listen(8081);
io.sockets.on('connection', function (socket) {
console.log(socket.id + ' connected!');
socket.emit('startup', { message: 'Socket started!' });
socket.on('joinRoom', function(){
console.log(socket.id + ' joining room lobby'); // prints on every other request
socket.join('lobby');
});
socket.on('disconnect', function() {
console.log(socket.id + ' disconnected!');
});
});
客户端控制台:
Socket started!
(refreshed page)
Socket started!
服务器控制台:
UIBqVuOiF1fegMIMAAAB connected!
UIBqVuOiF1fegMIMAAAB joining room lobby
UIBqVuOiF1fegMIMAAAB disconnected!
(refreshed page)
x3nMilBOjjFVjBFJAAAC connected!
(after about a minute once the client window has been closed or refreshed)
x3nMilBOjjFVjBFJAAAC disconnected!
答案 0 :(得分:1)
比赛条件!尝试在客户端代码中执行以下操作:
socket = io.connect('example.com:8081'),
socket.on('connect', function () {
socket.on('startup', function(data) {
console.log(data.message);
});
socket.emit('joinRoom');
});