3

我正在使用 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'));
});
4

1 回答 1

5

默认情况下,每个连接到套接字(socket.io 服务器)的客户端都被分配到一个由空对象或数组表示的空房间,我现在不记得了。

这是我用于将客户加入房间的代码:

socket.room = "room1";
socket.join(socket.room);

这就是您发送消息的方式:socket.sockets.in(client.room).emit("update", "A person has connected to " + room.name + " room.");

我认为你错过了socket.room一点。看看这个存储库:https ://github.com/tamaspiros/advanced-chat

和相应的文章:

http://tamaspiros.co.uk/2013/07/15/advanced-chat-using-node-js-and-socket-io-episode-1/

于 2013-07-25T10:25:37.553 回答