我正在使用 socket.io/node.js/express。当我使用 socket.join('room') 加入 socket.io 房间时,它会注册房间,但用户只加入“房间”。
此命令显示所有房间,它返回“房间”和“”,即使我从未创建过“房间”:
console.log(io.sockets.manager.rooms); // ['room', '']
此命令显示客户端已加入的所有房间,并返回一个空字符串 '':
console.log(io.sockets.manager.roomClients[socket.id]); // ['']
此命令应向房间中的每个客户端广播一条消息。使用实际房间(data.chatroom)时失败。但是当你用null或 ''替换 data.chatroom 时,它会将消息广播到空字符串房间:
io.sockets.in(data.chatroom).emit('broadcast_message', {message: data.message, handle: data.handle});
任何帮助将不胜感激,这是非常奇怪的行为:(
编辑:这是相关的服务器代码
var express = require('express'),
app = express(),
http = require('http'),
server = http.createServer(app),
io = require('socket.io').listen(server),
routes = require('./routes'),
chatroom = require('./routes/chatroom'),
path = require('path');
io.configure(function () {
io.set("transports", ["xhr-polling"]);
io.set("polling duration", 10);
});
io.sockets.on('connection', function (socket) {
socket.on('join_room', function(data) {
socket.join(data.chatroom);
socket.emit('joined_room', data.chatroom);
});
socket.on('send_message', function (data) {
io.sockets.in(data.chatroom).emit('broadcast_message', {message: data.message, handle: data.handle});
});
});
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
app.get('/', routes.index);
app.get('/room/:chatroom', chatroom.create_room);
server.listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});