我设置了一个 GET 和一个 POST 路由,想法是 POST 到该路由会触发一个事件,而 GET 路由是一个服务器发送的事件流,每次触发 POSTed 事件时都会触发......但是,我认为我做错了什么,因为尽管只有一个事件流订阅者,但似乎经常添加事件侦听器......我做错了什么?
var events = require('events'),
EventEmitter = events.EventEmitter,
rr = new EventEmitter();
app.post('/api/:boardname/remoterefresh', function(req, res){
var boardname = req.param('boardname'),
data = new Date().getTime();
rr.emit("refresh-"+boardname, data)
res.json({data: data})
});
app.get('/api/:boardname/remoterefresh', function(req, res){
var boardname = req.param('boardname')
rr.on("refresh-"+boardname, function(data){
setTimeout(function(){
res.write('data: '+data+'\n\n');
}, 1000)
});
req.socket.setTimeout(Infinity);
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
res.write('\n');
req.on('close', function(){
console.log('closed')
rr.removeListener("refresh-"+boardname, function(){
//
})
})
})