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

前端 未结 6 1445
南方客
南方客 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:35

    Here is an express server that sends one Server-Sent Event (SSE) per second, counting down from 10 to 0:

    const express = require('express')
    
    const app = express()
    app.use(express.static('public'))
    
    app.get('/countdown', function(req, res) {
      res.writeHead(200, {
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache',
        'Connection': 'keep-alive'
      })
      countdown(res, 10)
    })
    
    function countdown(res, count) {
      res.write("data: " + count + "\n\n")
      if (count)
        setTimeout(() => countdown(res, count-1), 1000)
      else
        res.end()
    }
    
    app.listen(3000, () => console.log('SSE app listening on port 3000!'))
    

    Put the above code into a file (index.js) and run it: node index

    Next, put the following HTML into a file (public/index.html):

    
    
      
    
    
      

    SSE:

    Data:

    In your browser, open localhost:3000 and watch the SSE countdown.

提交回复
热议问题