2014-09-05 132 views
1

如何將消息發送到動態會議室,以及當服務器收到該消息時,將該消息發送給其他會員的同一會議室?socket.io動態發送和回覆消息

table_id空間,它會動態地進行設定..

客戶:

var table_id = 1; // example, python will give this value 

var socket = io('http://localhost:3000'); 
socket.on('connect', function() { 
    console.log('Connected'); 
    socket.emit('join', "table_"+table_id); 
}); 

socket.on("table_"+table_id, function(data) { 
    console.log('New data:', data); 
}); 

$('button').on('click', function(){ 
    // send message to that room 
}); 

服務器:

io.on('connection', function(socket){ 

    socket.on('join', function(table) { 
    console.log('joined to table '+table); 
    socket.join(table); 
    }); 

    // when receive message from particular room, send it back to others in same room 

}); 

回答

1

也許你需要的命名空間,而不是房間。 您可以在此房間內的所有會員在一個名稱空間中廣播活動。

http://socket.io/docs/rooms-and-namespaces/

但是,如果你想要做經典的聊天消息,只廣播消息到整個房間:

io.to('some room').emit('some event'); 

例如:

io.on('connection', function(socket){ 
    socket.on('join', function(table) { 
     console.log('joined to table '+table); 
     socket._room = table 
     socket.join(table); 
    }); 
    // when receive message from particular room, send it back to others in same room 
    socket.on('message', function(message) { 
     io.to(socket._room).emit('some event',message); 
    }); 
}); 

和客戶端:

$('button').on('click', function(){ 
    // send message to that room 
    socket.emit('message', $('.message').val()); 
}); 
+0

謝謝s,這工作正常..但爲什麼我應該在這裏使用命名空間,動態的房間?你能給我舉例命名空間嗎? – 2014-09-05 13:17:37

+0

如果作品,不是,你不能;這是另一種方法。 – ainu 2014-09-05 13:21:33

+0

有一個樣本,不如房間好,但它是另一種情況:https://gist.github.com/ramainen/3c738641fc7fbe3ca6fc – ainu 2014-09-05 13:30:15

相關問題