Pergunta

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?

Foi útil?

Solução

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");
    });
  });
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top