File
Blob: samples/eventsource/server.js
| 1 | // Copyright (c) 2017-2024 Cloudflare, Inc. |
| 2 | // Licensed under the Apache 2.0 license found in the LICENSE file or at: |
| 3 | // https://opensource.org/licenses/Apache-2.0 |
| 4 | |
| 5 | // This is a simple SSE server written for Node.js ... it sends a message every second |
| 6 | // for 10 seconds, then disconnects. The worker.js file will use the EventSource API to |
| 7 | // connect to this server. |
| 8 | |
| 9 | const { createServer } = require('http'); |
| 10 | |
| 11 | let counter = 0; |
| 12 | |
| 13 | function getMessage(txt) { |
| 14 | return `data: ${txt}\nid: ${counter++}\n\n`; |
| 15 | } |
| 16 | |
| 17 | const server = createServer((req, res) => { |
| 18 | res.writeHead(200, { |
| 19 | 'Content-Type': 'text/event-stream', |
| 20 | 'Cache-Control': 'no-cache', |
| 21 | 'Connection': 'keep-alive' |
| 22 | }); |
| 23 | |
| 24 | res.write(getMessage('Hello World')); |
| 25 | |
| 26 | let t = setInterval(() => { |
| 27 | res.write(getMessage('Hello World')); |
| 28 | if (counter === 10) { |
| 29 | clearInterval(t); |
| 30 | res.end(); |
| 31 | counter = 0; |
| 32 | } |
| 33 | }, 1000); |
| 34 | }); |
| 35 | |
| 36 | server.listen(8888, () => { |
| 37 | console.log('Server is running...'); |
| 38 | }); |