|
| 1 | +// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file |
| 2 | +// for details. All rights reserved. Use of this source code is governed by a |
| 3 | +// BSD-style license that can be found in the LICENSE file. |
| 4 | + |
| 5 | +import 'dart:io'; |
| 6 | + |
| 7 | +import 'package:http_multi_server/http_multi_server.dart'; |
| 8 | +import 'package:shelf/shelf_io.dart'; |
| 9 | +import 'package:sse/server/sse_handler.dart'; |
| 10 | + |
| 11 | +SseHandler _sseHandler = SseHandler(Uri.parse('/test')); |
| 12 | + |
| 13 | +/// A backend for the Dart Debug Extension which sets up an SSE handler. |
| 14 | +/// |
| 15 | +/// The SSE handler simply sends a simple message and prints the response when |
| 16 | +/// a client connects. |
| 17 | +class ExtensionBackend { |
| 18 | + final String hostname; |
| 19 | + final int port; |
| 20 | + final HttpServer _server; |
| 21 | + |
| 22 | + ExtensionBackend._(this.hostname, this.port, this._server) { |
| 23 | + _listen(); |
| 24 | + } |
| 25 | + |
| 26 | + // Starts the backend on an open port. |
| 27 | + static Future<ExtensionBackend> start() async { |
| 28 | + var server = await HttpMultiServer.bind('localhost', 0); |
| 29 | + serveRequests(server, _sseHandler.handler); |
| 30 | + return ExtensionBackend._(server.address.host, server.port, server); |
| 31 | + } |
| 32 | + |
| 33 | + Future<void> close() async { |
| 34 | + await _server.close(); |
| 35 | + } |
| 36 | + |
| 37 | + void _listen() async { |
| 38 | + var connections = _sseHandler.connections; |
| 39 | + while (await connections.hasNext) { |
| 40 | + var connection = await connections.next; |
| 41 | + connection.sink.add('foo'); |
| 42 | + connection.stream.listen(print); |
| 43 | + } |
| 44 | + } |
| 45 | +} |
0 commit comments