在数组中维护名称空间不起作用

Maintaining Namespaces in an Array doesn't work

本文关键字:空间 不起作用 维护 数组      更新时间:2023-09-26

我正在制作一个由几个命名空间划分的聊天应用程序,换句话说,我想划分兴趣,其中一些喜欢谈论'狗'其他想谈论'猫'等等…

这是我的第一个版本,其中我将每个名称空间存储在一个变量中(它工作得很好):

服务器端:

var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);

app.get('/default', function(req, res){
  res.sendfile('index1.html');
});
app.get('/dog', function(req, res){
  res.sendfile('index2.html');
});
app.get('/', function(req, res){
  res.sendfile('index.html');
});

var cns1 =  io.of('/default');
//default nsp
cns1.on('connection', function(socket){
  socket.on('chat message', function(msg){
    cns1.emit('chat message', msg);
  });
});

var cns2 =  io.of('/dog');
//dog nsp
cns2.on('connection', function(socket){
  socket.on('chat message', function(msg){
    cns2.emit('chat message', msg);
  });
});
var cnsindex =  io.of('/');
//index nsp
cnsindex.on('connection', function(socket){
  socket.on('chat message', function(msg){
    cnsindex.emit('chat message', msg);
  });
});

http.listen(3000,function(){
  console.log('listening on *:3000');
});

索引* .html

    <script>
          //on index.html
          var socket = io.connect('http://localhost:3000/');
          //on index2.html
          //var socket = io.connect('http://localhost:3000/dog');
          //on index1.html
          //var socket = io.connect('http://localhost:3000/default');
$(function(){     
$('#bb').click(function (){
            socket.emit('chat message', $('#m').val());
            $('#m').val('');
            return false;
});
});
socket.on('chat message', function(msg){
    $('#messages').append($('<li>').text(msg));
  });


        </script>

每个命名空间都保持其消息的私密性。

现在,当我想将所有工作区存储在一个数组中以避免重复事件时,就像这样:

var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);

app.get('/default', function(req, res){
  res.sendfile('index1.html');
});
app.get('/dog', function(req, res){
  res.sendfile('index2.html');
});
app.get('/', function(req, res){
  res.sendfile('index.html');
});


var nss = [
    io.of('/default'),
    io.of('/dog'),
    io.of('/')
];

for (i in nss) 
{
    nss[i].on('connection', function(socket){
            socket.on('chat message', function(msg){
              nss[i].emit('chat message', msg);
            });
        });  
}

http.listen(3000,function(){
  console.log('listening on *:3000');
});

在第二个版本中不接收/dog/default url的消息,它允许从/dog/default发送消息到/

我被困在这里了,请帮帮我!

解决了,这是@levi:

造成的闭包问题
for (i in namespaces) 
{
    namespaces[i].on('connection',handleConnection(namespaces[i]));  
    function handleConnection(ns)
    {
        return function (socket){
                    socket.on('chat message', function(msg){
                      ns.emit('chat message', msg);
                    });
                }
    }

}

现在我的代码工作了:)