center.dart 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import 'dart:convert';
  2. import 'package:fis_common/logger/logger.dart';
  3. import 'package:fis_jsonrpc/services/notificationdecoder.dart';
  4. import 'connection.dart';
  5. import 'core/center.dart';
  6. import 'core/interface/connection.dart';
  7. import 'handler.dart';
  8. /// WebSocket消息中心
  9. class WsNotificationCenter extends NotificationCenter {
  10. String? _host;
  11. WsConnection? _connection;
  12. WsNotificationCenter() {
  13. NotificationDecoder.setup();
  14. }
  15. @override
  16. IConnection? get connection => _connection;
  17. String get host => _host ?? '';
  18. /// 设置主机地址
  19. ///
  20. /// [host] 主机地址
  21. void setHost(String host) {
  22. _host = host;
  23. }
  24. /// 注册消息处理器
  25. ///
  26. /// [handler] 消息处理器
  27. void register<T>(NotificationHandler<T> handler) {
  28. handlerDispatcher.register(handler);
  29. }
  30. @override
  31. void start() {
  32. logger.i("Start WsNotificationCenter");
  33. _buildConnection();
  34. super.start();
  35. }
  36. @override
  37. void stop() {
  38. if (_connection == null) return;
  39. logger.i("Stop WsNotificationCenter");
  40. super.stop();
  41. }
  42. @override
  43. void process(String data) {
  44. final jsonMap = jsonDecode(data);
  45. final typeInt = jsonMap['NotificationType'] as int;
  46. logger.i('WsNotificationCenter received a message, type: $typeInt.');
  47. final handler = handlerProvider.getHandler(typeInt);
  48. if (handler != null) {
  49. final message = NotificationDecoder.decode(jsonMap);
  50. handler.execute(message);
  51. logger.i('WsNotificationCenter message[type-$typeInt] handled.');
  52. }
  53. }
  54. void _buildConnection() {
  55. if (_host == null || _host!.isEmpty) {
  56. throw Exception("WsNotificationCenter host is not valid.");
  57. }
  58. if (_connection == null) {
  59. _connection = WsConnection(_host!);
  60. } else {
  61. if (_connection!.host != _host) {
  62. _connection!.close();
  63. _connection = WsConnection(_host!);
  64. }
  65. }
  66. }
  67. }
  68. enum WSType {
  69. Main,
  70. Consultation,
  71. Course,
  72. }