1

flutter websocket 中 服务端推送数据给客户端后 很多人的处理居然都是 if / switch; 感觉这样的写法不咋好!

自己想的一个办法:
lib 目录下新建一个 socket 目录 里面创建两个文件main.dartrouter.dart;
main.dart : 主要控制websocket的连接 断开 和收到消息的处理;
router.dart 则为websocket 服务端返回的消息做路由处理;

router.dart

import 'package:lee/logic/user.dart';

typedef void RouteHandle(Map params);

var wsRouter = new WsRouter();

class WsRouter {
  static Map<String, RouteHandle> _routers = new Map();

  init() {
    routers.forEach((route) {
      route.forEach((name, value) {
        this.add(name, value);
      });
    });
  }

  // 增加路由
  void add(String name, RouteHandle handle) {
    WsRouter._routers[name] = handle;
  }

  // 路由处理
  Future<void> handle(String name, Map params) async {
    RouteHandle handle = WsRouter._routers[name];
    if (handle == null) {
      print("路由不存在");
      return;
    }
    handle(params);
  }
}

List<Map<String, RouteHandle>> routers = [
  {"login": UserLogic.login},
  {"kick": UserLogic.kick},
];

main.dart

import 'package:lee/socket/router.dart';
import 'package:web_socket_channel/io.dart';
import 'dart:convert';

var webSocket = new WebSocket();

class WebSocket {
  // webSocket连接
  IOWebSocketChannel webSocketChannel;

  factory WebSocket() => _webSocket();

  static WebSocket _instance;

  // 构造函数
  WebSocket._() {
    // 初始化webSocket路由
    wsRouter.init();
  }

  static WebSocket _webSocket() {
    if (_instance == null) {
      _instance = WebSocket._();
    }
    return _instance;
  }

  conn() {
    IOWebSocketChannel channel = new IOWebSocketChannel.connect(
        "ws://127.0.0.1:8080/ws",
        pingInterval: Duration(milliseconds: 100));

    channel.stream
        .listen((data) => onMessage(data), onError: onError, onDone: onDone);

    this.webSocketChannel = channel;
  }

  onMessage(response) async {
    // 例如服务端返回的大概是这样一个json
    // {"cmd":"kick","data":{}}
    // {"cmd":"login","data":{}}
    Map params = json.decode(response);
    wsRouter.handle(params["cmd"], params["data"]);
  }

  onError(err) async {}

  onDone() async {}
}

如果对您有帮助请点个赞/收藏
如果代码/逻辑有问题 请指正!


孤独的根号3
1.8k 声望368 粉丝

提升就是一个不懂到懂的过程;