client_base.dart 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. import 'dart:convert';
  2. import 'package:dio/dio.dart' as dio;
  3. import 'package:flutter/foundation.dart';
  4. import 'exception.dart';
  5. import 'http_pool.dart';
  6. import 'interceptor.dart';
  7. import 'request.dart';
  8. // ignore: unused_element
  9. const _C_DIO_FUTURE_ERR_MSG = "Future already completed";
  10. const _C_DIO_FUTURE_ERR_KEYWORDS = "browser_adapter";
  11. /// JSON-RPC Client 基类
  12. class JsonRpcClientBase {
  13. /// 默认超时时间
  14. // ignore: non_constant_identifier_names
  15. static int DEAULT_TIMEOUT = 3000;
  16. late int _timeout;
  17. late String _serviceName;
  18. /// 服务主机地址
  19. final String host;
  20. /// 自定义Http header
  21. final Map<String, String>? headers;
  22. /// 超时时间(ms)
  23. int get timeout => _timeout;
  24. /// 服务名称
  25. String get serviceName => _serviceName;
  26. /// 服务请求地址
  27. String get servicePath =>
  28. host.endsWith('/') ? "$host$serviceName" : "$host/$serviceName";
  29. JsonRpcClientBase(
  30. this.host,
  31. String serviceName, {
  32. this.headers,
  33. int? timeout,
  34. }) {
  35. _timeout = timeout ?? DEAULT_TIMEOUT;
  36. _serviceName = serviceName;
  37. }
  38. void setTimeout(int milliseconds) {}
  39. /// 设置服务名
  40. void setServiceName(String name) => _serviceName = name;
  41. /// 请求RPC method
  42. @protected
  43. Future<dynamic> call(String method, [args]) async {
  44. var request = JsonRpcRequest(method, args);
  45. return _transmit(request);
  46. }
  47. /// 通知 RPC method
  48. @protected
  49. void notify(String method, [args]) {
  50. var request = JsonRpcRequest(method, args, notify: true);
  51. _transmit(request);
  52. }
  53. Future<dynamic> _transmit(JsonRpcRequest request) async {
  54. final req = await jsonRpcInterceptHost.onRequestTransmit(request);
  55. String package = jsonEncode(req.toJson());
  56. var response = await _postRequest(package);
  57. if (response == null) throw JsonRpcException(message: "Response Empty");
  58. var result = await _handleDecoded(response);
  59. return result;
  60. }
  61. Future<dynamic> _postRequest(String package) async {
  62. try {
  63. final httpClient = jrpcHttpPool.getClient(
  64. this.host,
  65. timeout: this.timeout,
  66. headers: this.headers,
  67. );
  68. var response =
  69. await httpClient.post('/${this.serviceName}', data: package);
  70. if (response.statusCode != 200) {
  71. throw JsonRpcException(
  72. message: "Http error.Status coder: ${response.statusCode}.");
  73. }
  74. return response.data;
  75. } on dio.DioError catch (e) {
  76. throw JsonRpcException(message: "Http error", data: e);
  77. } on StateError catch (e) {
  78. if (e.message == _C_DIO_FUTURE_ERR_MSG) {
  79. if (e.stackTrace != null &&
  80. e.stackTrace.toString().contains(_C_DIO_FUTURE_ERR_KEYWORDS)) {
  81. // don't rethrow
  82. }
  83. }
  84. }
  85. }
  86. Future<dynamic> _handleDecoded(Map<String, dynamic> response) async {
  87. final res = await jsonRpcInterceptHost.onResponse(response);
  88. if (res.containsKey('error')) {
  89. var error = JsonRpcServerError.fromJson(res['error']);
  90. error = await jsonRpcInterceptHost.onResponseError(error);
  91. throw error;
  92. }
  93. var result = res['result'];
  94. result = await jsonRpcInterceptHost.onResponseResult(result);
  95. return result;
  96. }
  97. }
  98. abstract class JsonRpcRequestModelBase {
  99. /// 转成Json Map
  100. Map<String, dynamic> toJson();
  101. }