乐闻世界logo
搜索文章和话题

How to fire EventSource SSE events?

1个答案

1

EventSource is a built-in browser API used to establish persistent connections to the server, enabling the server to send events via the Server-Sent Events (SSE) protocol. SSE allows the server to push real-time updates to the client.

The following are the steps for the server to send SSE events:

1. Creating Server-Side Code

The server-side requires a route to handle SSE connections and send events. In Node.js, this might look like:

javascript
const express = require('express'); const app = express(); app.get('/events', function(req, res) { // Set response headers to specify content type and allow CORS res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive', 'Access-Control-Allow-Origin': '*', }); // Send a simple event const id = Date.now(); res.write(`id: ${id}\n`); res.write("data: Hello, World!\n\n"); // Send a new event at regular intervals const intervalId = setInterval(() => { const eventId = Date.now(); res.write(`id: ${eventId}\n`); res.write(`data: ${new Date().toLocaleTimeString()}\n\n`); }, 1000); // Clear the interval when the client disconnects req.on('close', () => { clearInterval(intervalId); }); }); const PORT = 3000; app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); });

2. Creating Client-Side Code

On the client side, you need to create an instance of EventSource and specify the URL of the server-side SSE route:

javascript
const evtSource = new EventSource('http://localhost:3000/events'); evtSource.onmessage = function(event) { console.log('New message:', event.data); }; evtSource.onopen = function(event) { console.log('Connection to server opened.'); }; evtSource.onerror = function(event) { console.error('EventSource failed.'); }; // Ensure to close the connection when no longer needed window.onunload = function() { evtSource.close(); };

The server sends events to the client through continuous write operations, while the client receives these events via event listeners. Each event sent by the server includes a 'data:' field to transmit the message content, an optional 'id:' field to set the event ID (which can be used for resuming connections after disconnection), and an optional 'event:' field to specify the event type (if not specified, the default event type is 'message').

Each message sent to the client ends with two newline characters (\n\n), which is the message terminator specified by the SSE protocol.

By following these steps, we can implement a basic SSE communication. Of course, in practical applications, you may need to handle more complex scenarios, such as reconnection after disconnection, user authentication, and optimizing server-side resource management.

2024年6月29日 12:07 回复

你的答案