0
我有一個節點快遞服務器,我將其用作後端以支持我網站上的即時聊天功能。我遇到的問題是有人關閉瀏覽器,他們的狀態不會更新到他們朋友的好友列表中的「離線」。我知道節點中有一個函數叫做req.on('close',function(){});但我不確定如何將其包含在我的服務器文件中。任何提示正確的方向將不勝感激。以下是我認爲相關的快遞服務器代碼片段:如何知道用戶何時與快遞服務器斷開連接
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;在中間件中處理 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);
下面是使用'socket.io'進行聊天的說明:http://net.tutsplus.com/tutorials/javascript-ajax/real-time-chat-with-nodejs-socket-io-and-expressjs/和視頻:http://www.youtube.com/watch?v = pNKNYLv2BpQ – KayakDave
您是否知道用socket.io替換客戶端代碼中的Ajax調用是否很困難?我認爲這是我絕對需要做的事情。 Socket.io似乎好多了。 –
@ArjunPatel取決於你的AJAX調用的複雜性,但通常不是一個大問題。 – robertklep