Browse Source

remove old listener

Melon 2 years ago
parent
commit
adf897bd9f
3 changed files with 44 additions and 227 deletions
  1. 0 20
      lib/listener/handler.dart
  2. 0 159
      lib/listener/listener.dart
  3. 44 48
      lib/rpc.dart

+ 0 - 20
lib/listener/handler.dart

@@ -1,20 +0,0 @@
-import 'package:fis_jsonrpc/services/notification.m.dart'
-    show NotificationTypeEnum;
-
-export 'package:fis_jsonrpc/services/notification.m.dart'
-    show MessageTypeEnum, NotificationTypeEnum, NotifyMessage;
-
-abstract class JsonRpcNotificationHandlerBase {
-  JsonRpcNotificationHandlerBase(this.type, {this.order = 0});
-
-  /// Remote notification type.
-  final NotificationTypeEnum type;
-
-  /// For set order of handling notification.
-  final int order;
-
-  /// Handle notification.
-  ///
-  /// [message] The message content of notification.
-  Future<void> handle(String? message);
-}

+ 0 - 159
lib/listener/listener.dart

@@ -1,159 +0,0 @@
-import 'dart:convert';
-import 'dart:typed_data';
-
-import 'package:fis_common/logger/logger.dart';
-import 'package:web_socket_channel/web_socket_channel.dart';
-import 'package:web_socket_channel/status.dart' as wsStatus;
-
-import 'handler.dart';
-
-export 'handler.dart';
-
-/// Listener for listening remote notification.
-class JsonRpcNotificationListener {
-  JsonRpcNotificationListener({
-    required this.host,
-    required this.port,
-    this.protocol = "ws",
-    this.token,
-  });
-
-  /// Web Socket protocol. Default value is ['ws'].
-  final String protocol;
-
-  /// Web Socket host.
-  final String host;
-
-  /// Web Socket port.
-  final int port;
-
-  /// A sign for relating to the target communication. It's [nullable].
-  final String? token;
-
-  WebSocketChannel? _channel;
-
-  final _handlersMap =
-      <NotificationTypeEnum, Set<JsonRpcNotificationHandlerBase>>{};
-
-  int _retryCount = 0;
-  static const _retryLimit = 5;
-
-  /// Registered handler intance list.
-  List<JsonRpcNotificationHandlerBase> get handlers =>
-      _handlersMap.entries.expand((e) => e.value).toList();
-
-  /// Status of running.
-  bool get running => _channel != null && _channel!.closeCode == null;
-
-  /// Start listen remote notifications.
-  void run() {
-    _channel = WebSocketChannel.connect(Uri.parse(_buildConnectUrl()));
-    _channel!.stream.listen(
-      (data) {
-        if (!running) return; // diable inner 5s's retention.
-
-        final message = _parseMessageData(data);
-        if (message != null) {
-          _handleNotification(message);
-        }
-      },
-      onError: (error) {
-        logger.e("[JsonRpcListener] websocket errror.", error);
-        _retry(error);
-      },
-    );
-    logger.i("[JsonRpcListener] ran.");
-  }
-
-  /// Add notification-handler.
-  ///
-  /// [handler] A notification-handler instance extends class [JsonRpcNotificationHandlerBase].
-  void addHandler<T extends JsonRpcNotificationHandlerBase>(
-    T handler,
-  ) {
-    final type = handler.type;
-    if (!_handlersMap.containsKey(type)) {
-      _handlersMap[type] = {};
-    }
-    final set = _handlersMap[type]!;
-    set.add(handler);
-  }
-
-  /// Remove target notification-handler.
-  ///
-  /// [type] The type of message for targeting handlers.
-  void removeHandler<T extends JsonRpcNotificationHandlerBase>(
-      NotificationTypeEnum type) {
-    if (!_handlersMap.containsKey(type)) return;
-
-    final set = _handlersMap[type]!;
-    set.removeWhere((e) => e is T);
-  }
-
-  /// Close and dispose connection/other resources.
-  Future<void> close() async {
-    if (_channel != null) {
-      if (_channel!.closeCode == null) {
-        await _channel!.sink.close(wsStatus.normalClosure);
-      }
-      _channel = null;
-    }
-  }
-
-  void _retry(dynamic error) {
-    // https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent/code
-    _channel?.sink.close(1013); // code: try again later.
-    _channel = null;
-
-    if (_retryLimit > _retryCount) {
-      Future.delayed(const Duration(seconds: 1), () {
-        _retryCount++;
-        run();
-      });
-    }
-  }
-
-  String _buildConnectUrl() {
-    final originUrl = "$protocol://$host:$port";
-    final url =
-        token == null || token!.isEmpty ? originUrl : "$originUrl?token=$token";
-    return url;
-  }
-
-  NotifyMessage? _parseMessageData(dynamic data) {
-    try {
-      final uint8Array = Uint8List.fromList(data);
-      final byteData = uint8Array.buffer.asByteData();
-      final messageType = byteData.getUint8(0);
-      final notifyType = byteData.getUint8(1);
-      final messageLength = byteData.getUint8(2);
-      final messageConentList =
-          Uint8List.view(uint8Array.buffer, 6, messageLength);
-      final messageConent = Uint8List.fromList(messageConentList);
-      final messageText = const Utf8Decoder().convert(messageConent);
-
-      return NotifyMessage(
-        length: messageLength,
-        messageType: MessageTypeEnum.values[messageType],
-        notificationType: NotificationTypeEnum.values[notifyType],
-        message: messageText,
-      );
-    } catch (e) {
-      logger.e("[JsonRpcListener] parse message data error.", e);
-    }
-    return null;
-  }
-
-  void _handleNotification(NotifyMessage message) async {
-    final type = message.notificationType;
-    if (!_handlersMap.containsKey(type)) return;
-
-    final set = _handlersMap[type]!;
-    final orderedHandlers = set.toList()
-      ..sort((a, b) => a.order.compareTo(b.order));
-
-    for (var handler in orderedHandlers) {
-      await handler.handle(message.message);
-    }
-  }
-}

+ 44 - 48
lib/rpc.dart

@@ -13,7 +13,6 @@ export 'services/index.dart';
 export 'request.dart';
 export 'exception.dart';
 export 'interceptor.dart';
-export 'listener/listener.dart';
 
 typedef T ServiceBuilder<T extends JsonRpcClientBase>();
 
@@ -53,75 +52,72 @@ class JsonRpcProxy {
     return _platformService!;
   }
 
-	AIDiagnosisService get aIDiagnosis =>
-	findService(() => new AIDiagnosisService(currentHostAddress));
+  AIDiagnosisService get aIDiagnosis =>
+      findService(() => new AIDiagnosisService(currentHostAddress));
 
-	ASRService get aSR =>
-	findService(() => new ASRService(currentHostAddress));
+  ASRService get aSR => findService(() => new ASRService(currentHostAddress));
 
-	AuthenticationService get authentication =>
-	findService(() => new AuthenticationService(currentHostAddress));
+  AuthenticationService get authentication =>
+      findService(() => new AuthenticationService(currentHostAddress));
 
-	ConnectService get connect =>
-	findService(() => new ConnectService(currentHostAddress));
+  ConnectService get connect =>
+      findService(() => new ConnectService(currentHostAddress));
 
-	DeviceService get device =>
-	findService(() => new DeviceService(currentHostAddress));
+  DeviceService get device =>
+      findService(() => new DeviceService(currentHostAddress));
 
-	EmailService get email =>
-	findService(() => new EmailService(currentHostAddress));
+  EmailService get email =>
+      findService(() => new EmailService(currentHostAddress));
 
-	IdentityApplyService get identityApply =>
-	findService(() => new IdentityApplyService(currentHostAddress));
+  IdentityApplyService get identityApply =>
+      findService(() => new IdentityApplyService(currentHostAddress));
 
-	LoginService get login =>
-	findService(() => new LoginService(currentHostAddress));
+  LoginService get login =>
+      findService(() => new LoginService(currentHostAddress));
 
-	OrganizationService get organization =>
-	findService(() => new OrganizationService(currentHostAddress));
+  OrganizationService get organization =>
+      findService(() => new OrganizationService(currentHostAddress));
 
-	PatientService get patient =>
-	findService(() => new PatientService(currentHostAddress));
+  PatientService get patient =>
+      findService(() => new PatientService(currentHostAddress));
 
-	PositionService get position =>
-	findService(() => new PositionService(currentHostAddress));
+  PositionService get position =>
+      findService(() => new PositionService(currentHostAddress));
 
-	RankService get rank =>
-	findService(() => new RankService(currentHostAddress));
+  RankService get rank =>
+      findService(() => new RankService(currentHostAddress));
 
-	RecordInfoService get recordInfo =>
-	findService(() => new RecordInfoService(currentHostAddress));
+  RecordInfoService get recordInfo =>
+      findService(() => new RecordInfoService(currentHostAddress));
 
-	RegionService get region =>
-	findService(() => new RegionService(currentHostAddress));
+  RegionService get region =>
+      findService(() => new RegionService(currentHostAddress));
 
-	RemedicalService get remedical =>
-	findService(() => new RemedicalService(currentHostAddress));
+  RemedicalService get remedical =>
+      findService(() => new RemedicalService(currentHostAddress));
 
-	ReportService get report =>
-	findService(() => new ReportService(currentHostAddress));
+  ReportService get report =>
+      findService(() => new ReportService(currentHostAddress));
 
-	RoleService get role =>
-	findService(() => new RoleService(currentHostAddress));
+  RoleService get role =>
+      findService(() => new RoleService(currentHostAddress));
 
-	SMSService get sMS =>
-	findService(() => new SMSService(currentHostAddress));
+  SMSService get sMS => findService(() => new SMSService(currentHostAddress));
 
-	StorageService get storage =>
-	findService(() => new StorageService(currentHostAddress));
+  StorageService get storage =>
+      findService(() => new StorageService(currentHostAddress));
 
-	UserService get user =>
-	findService(() => new UserService(currentHostAddress));
+  UserService get user =>
+      findService(() => new UserService(currentHostAddress));
 
-	VinnoServerService get vinnoServer =>
-	findService(() => new VinnoServerService(currentHostAddress));
+  VinnoServerService get vinnoServer =>
+      findService(() => new VinnoServerService(currentHostAddress));
 
-	DBLogService get dBLog =>
-	findService(() => new DBLogService(currentHostAddress));
-
-	LiveConsultationService get liveConsultation =>
-	findService(() => new LiveConsultationService(currentHostAddress));
+  DBLogService get dBLog =>
+      findService(() => new DBLogService(currentHostAddress));
 
+  LiveConsultationService get liveConsultation =>
+      findService(() => new LiveConsultationService(currentHostAddress));
 
   /// 设置服务主机地址
   void setServerHost(String address) {