server.dart 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import 'dart:async' show Future;
  2. import 'dart:convert';
  3. import 'dart:io';
  4. import 'dart:isolate';
  5. final _procNumber = Platform.numberOfProcessors;
  6. final _encoder = JsonUtf8Encoder();
  7. void main(List<String> args) {
  8. var errorPort = ReceivePort();
  9. errorPort.listen((e) => print(e));
  10. for (var i = 1; i < _procNumber; i++) {
  11. Isolate.spawn(_startInIsolate, [], onError: errorPort.sendPort);
  12. }
  13. _startInIsolate([]);
  14. }
  15. void _startInIsolate(List args) {
  16. _startServer();
  17. }
  18. Future<void> _startServer() async {
  19. final server = await HttpServer.bind('0.0.0.0', 8080, shared: true);
  20. server.defaultResponseHeaders.clear();
  21. server.serverHeader = 'dart';
  22. server.listen((request) {
  23. switch (request.uri.path) {
  24. case '/json':
  25. _jsonTest(request);
  26. break;
  27. case '/plaintext':
  28. _plaintextTest(request);
  29. break;
  30. default:
  31. _sendResponse(request, HttpStatus.notFound);
  32. break;
  33. }
  34. });
  35. }
  36. /// Completes the given [request] by writing the [bytes] with the given
  37. /// [statusCode] and [type].
  38. void _sendResponse(
  39. HttpRequest request,
  40. int statusCode, {
  41. ContentType? type,
  42. List<int>? bytes,
  43. }) {
  44. final response = request.response;
  45. response
  46. ..statusCode = statusCode
  47. ..headers.date = DateTime.now();
  48. if (type != null) {
  49. response.headers.contentType = type;
  50. }
  51. if (bytes != null) {
  52. response
  53. ..contentLength = bytes.length
  54. ..add(bytes);
  55. } else {
  56. response.contentLength = 0;
  57. }
  58. response.close();
  59. }
  60. /// Completes the given [request] by writing the [response] as JSON.
  61. void _sendJson(HttpRequest request, Object response) => _sendResponse(
  62. request,
  63. HttpStatus.ok,
  64. type: ContentType.json,
  65. bytes: _encoder.convert(response),
  66. );
  67. /// Completes the given [request] by writing the [response] as plain text.
  68. void _sendText(HttpRequest request, String response) => _sendResponse(
  69. request,
  70. HttpStatus.ok,
  71. type: ContentType.text,
  72. bytes: utf8.encode(response),
  73. );
  74. /// Responds with the JSON test to the [request].
  75. void _jsonTest(HttpRequest request) =>
  76. _sendJson(request, const {'message': 'Hello, World!'});
  77. /// Responds with the plaintext test to the [request].
  78. void _plaintextTest(HttpRequest request) => _sendText(request, 'Hello, World!');