writeSSE method

Future<void> writeSSE(
  1. SseEvent event
)

Sends a structured SSE event to the client.

Multi-line SseEvent.data is split and prefixed correctly per the spec.

Implementation

Future<void> writeSSE(SseEvent event) async {
  if (_aborted) return;
  try {
    final buf = StringBuffer();
    if (event.id != null) buf.writeln('id: ${event.id}');
    if (event.event != null) buf.writeln('event: ${event.event}');
    if (event.retry != null) buf.writeln('retry: ${event.retry}');
    for (final line in event.data.split('\n')) {
      buf.writeln('data: $line');
    }
    buf.writeln(); // blank line terminates the event
    _res.write(buf.toString());
    await _res.flush();
  } on SocketException {
    _aborted = true;
    _onAbortCallback?.call();
  }
}