我正在将聊天应用程序划分为几个名称空间,换句话说我想分割兴趣,其中一些人喜欢谈论'狗'其他想要谈论'猫'等等......
这是我的第一个版本,其中我将每个命名空间存储在一个变量中(它完美地运行):
服务器端:
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
个网址的消息,并且允许从/dog
和/default
向/
发送消息。
我被困在这里,请帮忙!
答案 0 :(得分:0)
解决了,这是关闭@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);
});
}
}
}
现在我的代码工作了:)