开发者

Nodejs - how to make functions happen just once?

I got a simple chat app utilizing socket.io and express framework, below is part of the code:

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});
    });
});

You can see the res.header and res.send in the socket.on closure. Those "res" will execute constantly, and cause error "Can't set headers after they are s开发者_JAVA技巧ent."

I'm looking for a way to make the block-

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

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

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

-happen just once.


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});
    });
});

Use .once


Try moving the response headers out of the connection callback and into the "get /" callback:

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});
});

But the sequencing seems strange in your example. If you add a connection callback to the socket each time a new request is handled then you'll get a bunch of (potentially) conflicting session attributes. You may need to rethink things.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜