Created
March 13, 2025 11:07
-
-
Save ihsanberahim/7a755e0474e36e627f04a9a9bec414cf to your computer and use it in GitHub Desktop.
SSE NextJs & Flutter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:async'; | |
import 'package:meta/meta.dart'; | |
import 'package:universal_html/html.dart' as html; | |
class Sse { | |
final html.EventSource eventSource; | |
final StreamController<String> streamController; | |
Sse._internal(this.eventSource, this.streamController); | |
factory Sse.connect({ | |
@required Uri uri, | |
bool withCredentials = false, | |
bool closeOnError = true, | |
}) { | |
final streamController = StreamController<String>(); | |
final eventSource = html.EventSource(uri.toString(), withCredentials: withCredentials); | |
eventSource.addEventListener('message', (html.Event message) { | |
streamController.add((message as html.MessageEvent).data as String); | |
}); | |
///close if the endpoint is not working | |
if (closeOnError) { | |
eventSource.onError.listen((event) { | |
eventSource?.close(); | |
streamController?.close(); | |
}); | |
} | |
return Sse._internal(eventSource, streamController); | |
} | |
Stream get stream => streamController.stream; | |
bool isClosed() => this.streamController == null || this.streamController.isClosed; | |
void close() { | |
this.eventSource?.close(); | |
this.streamController?.close(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express'); | |
const app = express(); | |
const PORT = 3000; | |
app.get('/events', (req, res) => { | |
// Set SSE headers | |
res.setHeader('Content-Type', 'text/event-stream'); | |
res.setHeader('Cache-Control', 'no-cache'); | |
res.setHeader('Connection', 'keep-alive'); | |
// Initial message | |
res.write('data: Welcome to Server-Sent Events!\n\n'); | |
// Send messages every 5 seconds | |
const intervalId = setInterval(() => { | |
const message = { time: new Date().toISOString() }; | |
res.write(`data: ${JSON.stringify(message)}\n\n`); | |
}, 5000); | |
// Clean up on disconnect | |
req.on('close', () => { | |
clearInterval(intervalId); | |
res.end(); | |
}); | |
}); | |
app.listen(PORT, () => { | |
console.log(`SSE server running on http://localhost:${PORT}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment