node怎么返回Server-Sent
时间: 2024-06-11 19:05:58 浏览: 5
Events?
要返回 Server-Sent Events,您需要创建一个 HTTP 服务器,并在服务器上设置适当的路由处理程序。以下是一个示例:
```javascript
const http = require('http');
const server = http.createServer((req, res) => {
// 设置响应头
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
// 发送数据
res.write('data: hello\n\n');
// 定时发送数据
setInterval(() => {
res.write('data: ' + new Date().toISOString() + '\n\n');
}, 1000);
});
server.listen(3000, () => {
console.log('Server started on port 3000');
});
```
在上面的示例中,我们创建了一个 HTTP 服务器,并设置了适当的响应头以返回 Server-Sent Events。我们还在服务器上设置了一个定时器,每秒钟向客户端发送当前时间。
您可以使用浏览器中的 JavaScript 来订阅 Server-Sent Events。以下是一个示例:
```javascript
const source = new EventSource('/events');
source.addEventListener('message', (event) => {
console.log(event.data);
});
```
在上面的示例中,我们使用 `EventSource` 对象来订阅 `/events` 路径上的 Server-Sent Events。每次服务器发送数据时,`message` 事件将被触发,并且您可以在事件处理程序中使用 `event.data` 属性来访问数据。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)