Nodejs - 如何让函数只发生一次?

时间:2011-06-07 17:33:15

标签: node.js

我使用socket.io和express框架获得了一个简单的聊天应用程序,下面是代码的一部分:

var app = express.createServer();
var socket = io.listen(app);

var store = new express.session.MemoryStore;
app.use(express.cookieParser());
app.use(express.session({ 
    secret: 'something', 
    store: store, 
    cookie: { 
        maxAge: 60*60*24*30*1000
    }
}));

app.get('/', function(req, res){
    socket.on('connection', function(client) {
        req.session.ioid = client.sessionId;
        req.session.channel = req.param('channel');
        req.session.username = req.param('username');
        //I want the code below happen just once                
        res.header('Content-Type', 'text/plain');
        res.header('Access-Control-Allow-Origin', '*');
        res.send({sid:req.session.id});
    });
});

你可以在socket.on闭包中看到res.header和res.send。那些“res”将不断执行,并导致错误“无法在发送后设置标题。”

我正在寻找一种制作块的方法 -

res.header('Content-Type', 'text/plain');

res.header('Access-Control-Allow-Origin', '*');

res.send({sid:req.session.id});

- 只打一次。

2 个答案:

答案 0 :(得分:8)

app.get('/', function(req, res){
    socket.on("connection", function(client) {
        req.session.ioid = client.sessionId;
        req.session.channel = req.param('channel');
        req.session.username = req.param('username');
    });

    socket.once('connection', function(client) {
        //I want the code below happen just once                
        res.header('Content-Type', 'text/plain');
        res.header('Access-Control-Allow-Origin', '*');
        res.send({sid:req.session.id});
    });
});

使用.once

答案 1 :(得分:3)

尝试将响应标头移出连接回调并进入“get /”回调:

app.get('/', function(req, res){
    socket.on('connection', function(client) {
        req.session.ioid = client.sessionId;
        req.session.channel = req.param('channel');
        req.session.username = req.param('username');
    });
    res.header('Content-Type', 'text/plain');
    res.header('Access-Control-Allow-Origin', '*');
    res.send({sid:req.session.id});
});

但是你的例子中的排序似乎很奇怪。如果每次处理新请求时都向套接字添加连接回调,那么您将获得一堆(可能)冲突的会话属性。你可能需要重新考虑事情。