Simple Way to Implement Server Sent Events in Node.js?

前端 未结 6 1303
南方客
南方客 2021-01-31 06:11

I\'ve looked around and it seems as if all the ways to implement SSEs in Node.js are through more complex code, but it seems like there should be an easier way to send and recei

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-31 06:40

    **client.js**
    
    var eventSource = new EventSource("/route/events");
    eventSource.addEventListner("ping", function(e){log(e.data)});
    
    //if no events specified
    eventSource.addEventListner("message", function(e){log(e.data)});
    
    **server.js**
    
    http.createServer((req, res)=>{
    
        if(req.url.indexOf("/route/events")>=){
    
          res.setHeader('Connection', 'keep-alive');
    
          res.setHeader("Cache-Control", "no-cache");
    
          res.setHeader("Content-Type", "text/event-stream");
    
          let event = "event: ping";
    
          let id = `id: ${Date.now()}`;
    
          let data = {
             message:`hello @${new Date().toString()}`
          }
    
          data = "data: "+JSON.stringify(data);
    
          res.end(`${event}\n${id}\n${data}\n\n`);
       }
    }).listen(PORT)
    

提交回复
热议问题