我想知道如何在一個名稱空間中共享套接字中設置的數據並在另一個名稱空間上訪問它?Socket.io在名稱空間之間共享套接字數據
我完全知道我可以將數據附加到套接字對象本身。當我將數據附加到一個名稱空間並嘗試在另一個名稱空間上訪問它時,會出現問題。
下面說明問題
var io = require('socket.io');
module.exports.init = function(server) {
io = io.listen(server);
io.of('/chatSystem').on('connection', function(socket) {
/*handling set nickname event*/
socket.on('set.name', function(data) {
/*attach nickname key to this socket*/
socket.nickname = data.name;
socket.broadcast.emit('user.entered', data);
});
});
io.of('/chatUser').on('connection', function(socket) {
/*handling client event socket.send*/
socket.on('message', function(data) {
data = JSON.parse(data);
data.nickname = socket.nickname; // <--- this is undefined
/*send to all connected client(broadcast will not send message to socket that created the message)*/
socket.broadcast.send(JSON.stringify(data));
data.type = 'myMessage';
/*manually send back the message to the socket that created the message*/
socket.send(JSON.stringify(data));
});
});
};
是有辦法解決這一問題?
我面臨同樣的問題。當試圖在另一個命名空間中讀取時,在一個名稱命名空間中設置的名稱未定義。 如果所有的消息都只使用一個套接字'io.on('connection',function(){.....})'這個工作正常。但不能使用兩個不同的名稱空間。 –
我面臨同樣的問題,並希望對此有一個答案。 –