Write an example of a text event stream from an express server to a react client
- User
Write an example of a text event stream from an express server to a react client
Assistant
Below is a simplified example of how an Express server can send a text event stream to a React client using Server-Sent Events (SSE). This example will cover both the server-side (Express) and client-side (React) implementations.
Server-Side (Express)
First, ensure you have Node.js installed. Then, create a new project, initialize a new Node.js project with
npm init, and install Express:bashnpm init -y npm install expressCreate a file named
server.jsand add the following code:javascriptconst express = require('express'); const app = express(); const port = 3001; // Using a different port to not conflict with React's default port (3000) app.get('/events', (req, res) => { res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive', }); // Example: Send an event every 5 seconds const intervalId = setInterval(() => { const data = `data: ${new Date().toLocaleTimeString()}\n\n`; // SSE format requires "data: " prefix and "\n\n" at the end res.write(data); }, 5000); // Cleanup req.on('close', () => { clearInterval(intervalId); res.end(); }); }); app.listen(port, () => { console.log(`Server running on http://localhost:${port}`); });Client-Side (React)
Assuming you have a React project set up (if not, run
npx create-react-app my-appandcd my-appto create and navigate into one), open thesrc/App.jsfile and update it with the following code:jsx
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.