문제

I'm using Node.js and I want to send back multiple responses to the client. So the client will send an AJAX POST request and get back some data. But the server has to continue to do some processing and when that's done, I want it to send more data back.

I know this is a good candidate for Socket.io, but I haven't really seen an example of how to use socket.io in the context of an MVC framework. Does it go in the controller?

도움이 되었습니까?

해결책

You could use Server Sent Events. Here's an example:

https://github.com/chovy/nodejs-stream (full source code example)

UI

var source = new EventSource('stream');

source.addEventListener('a_server_sent_event', function(e) {
   var data = JSON.parse(e.data);
   //do something with data
});

Node

if ( uri == '/stream' ) {
  //setup http server response handling and get some data from another service
  http.get(options, function(resp){
    resp.on('data', function(chunk){
      res.write("event: a_server_sent_event\n");
      res.write("data: "+chunk.toString()+"\n\n");
    });
  });
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top