emit user-specific events for long poll
What's the best way to implement long-polling for user-specific events? I have a "home feed" for each user that I want dynamically updated with new information immediately as it comes in.
Right now I'm making an AJAX call from the client to /register?id=2, for example, to listen for updates. The server itself sends a GET request to /emit?id=2&eventid=3 when some other event(eventid=3) related to user(id=2) occurs. The Node.js server has code similar to below:
var event_emitter = new events.EventEmitter();
http.createServer(function(req,res) {
var uriParse = url.parse(req.url,true);
var pathname = uriParse.pathname;
if (pathname=="/register") {
var userid = uriParse.query.id;
var thisRes = res;
event_emitter.addListener('event'+userid,function(eventid){
if (thisRes) {
console.log(thisRes);
thisRes.writeHead(200, { "Content-Type": "text/plain" });
thisRes.end(eventid);
thisRes = null;
}
});
} else if (pathname=="/emit") {
var userid = uriParse.query.id;
var eventid = uriParse.query.eventid;
event_emitter.emit('event'+userid,eventid);
res.writeHead(200, { "Content-Type": "text/plain" });
res.end('success');
}
}).listen(3000,"0.0.0.0");
So the client's AJAX call doesn't load开发者_如何转开发 until the event occurs, at which point the server returns a response with the eventid. The client uses this eventid to make a different AJAX call (unrelated, since I'm using Django for the main application but Node.js for event-driven super-powers).
I'm just bothered by creating so many listeners for "event2" "event454" etc as more users connect. Is this scalable with something like Node.js? How else can I emit user-specific events?
Thanks in advance!
You can remove the listener after emitting the events using removeAllListeners
.
精彩评论