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

前端 未结 6 1290
南方客
南方客 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条回答
  •  北恋
    北恋 (楼主)
    2021-01-31 06:45

    I'm adding a simple implementation of SSE here. It's just one Node.js file.

    You can have a look at the result here: https://glossy-ox.glitch.me/

    const http = require('http');
    const port = process.env.PORT || 3000;
    
    const server = http.createServer((req, res) => {
      // Server-sent events endpoint
      if (req.url === '/events') {
        res.writeHead(200, {
          'Content-Type': 'text/event-stream',
          'Cache-Control': 'no-cache',
          'Connection': 'keep-alive',
        });
    
        const refreshRate = 1000; // in milliseconds
        return setInterval(() => {
          const id = Date.now();
          const data = `Hello World ${id}`;
          const message =
            `retry: ${refreshRate}\nid:${id}\ndata: ${data}\n\n`;
          res.write(message);
        }, refreshRate);
      }
    
      // Client side
      res.writeHead(200, {'Content-Type': 'text/html'});
      res.end(`
        
        
          
            
            SSE
          
          
            
    
          
          
        
      `);
    });
    
    server.listen(port);
    
    server.on('error', (err) => {
      console.log(err);
      process.exit(1);
    });
    
    server.on('listening', () => {
      console.log(`Listening on port ${port}`);
    });
    

提交回复
热议问题