Arjun Patel
Arjun Patel

Reputation: 266

How do I know when user disconnects with express server

I have an node express server that I use as a backend to support an instant chat feature on my website. The issue I have is when someone closes out their browser, their status does not get updated to 'offline' on their friend's buddy list. I know there is a function in node called req.on('close', function(){}); but I'm just not sure how to include it in my server file. Any hints in the right direction would be greatly appreciated. Here is a snippet of my express server code that I think is relevant:

var app = express();
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.bodyParser());    
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});

app.use(require('./middleware/im')({
maxAge: 60 * 1000,
reapInterval: 60 * 1000,
    authentication: require('./libs/authentication/' + AUTH_LIBRARY) 
}));


    app.set('root', __dirname);

// Listener endpoint; handled in middleware app.get('/listen', function(){});

app.post('/message', function(req, res) {
    res.find(req.body['to'], function(user) {
        if(!user)
           return res.send(new packages.Error('not online'));
        res.message(user, new packages.Message(
        req.session.data('username'),
        req.body.body
    ));


});

});

app.post('/message/typing', function(req, res) {
if(~packages.TYPING_STATES.indexOf('typing' + req.body['state'])) {
    res.find(req.body['to'], function(user) {
        if(user) {
            res.message(user, new packages.Status(
                req.session.data('username'),
                'typing' + req.body.state
            ));
        }

        // Typing updates do not receive confirmations,
        // as they are not important enough.
        res.send('');
    });
} else {
    res.send(new packages.Error('invalid state'));
}

});

app.post('/status', function(req, res) {

if(~packages.STATUSES.indexOf(req.body['status'])) {
    res.status(req.body.status, req.body.message);
    res.send(new packages.Success('status updated'));
} else {
    res.send(new packages.Error('invalid status'));
}
});



    app.post('/clear', function(req, res) {

    app.use(require('./middleware/im')({
       clear: req.sessionID,
       maxAge: 60 * 1000,
   reapInterval: 60 * 1000,
   authentication: require('./libs/authentication/' + AUTH_LIBRARY)
}));
    req.sessionID = null;
res.send(new packages.Success('cleared session'));
app.use(require('./middleware/im')({
   clear: 0,
       maxAge: 60 * 1000,
      reapInterval: 60 * 1000,
    authentication: require('./libs/authentication/' + AUTH_LIBRARY)

}));

});

app.post('/online', function(req, res) {
 var d = new Date();
  var n = d.getTime() + 60;
 req.sessionID.expires = n;
 res.status(req.body.status, 'available');
  res.send(new packages.Success('Online'));

});

app.post('/signoff', function(req, res) {
res.signOff();
res.send(new packages.Success('goodbye'));

});

https.createServer(options, app).listen(8000);

Upvotes: 1

Views: 578

Answers (1)

robertklep
robertklep

Reputation: 203251

HTTP is a stateless protocol, so it doesn't have any concept of 'connected user'. You need to use some sort of client-side mechanism to notify your server when a user is navigating away (perhaps use an onbeforeunload handler which posts a message to the server). The close event you mention isn't useful, unless you're using some sort of long-polling mechanism (but I don't think you are).

To implement chat, a better solution might be socket.io, which maintains a permanent connection between the browser and the server and has built-in mechanisms to notice if a browser has closed the connection (in case the user navigated away, for instance).

Upvotes: 3

Related Questions