Implementation of flutter Custom websocket Routing

  • 2021-11-13 18:23:57
  • OfStack

In flutter websocket, after the server pushes data to the client, many people's processing is actually if/switch; I feel that this writing is not so good!

One way I think of:

Create a new socket directory under lib and create two files main. dart and router. dart;
main. dart: Mainly controls the disconnection of websocket and the processing of received messages;
router. dart routes the messages returned by websocket server;

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);
   });
  });
 }

 //  Add route 
 void add(String name, RouteHandle handle) {
  WsRouter._routers[name] = handle;
 }

 //  Routing processing 
 Future<void> handle(String name, Map params) async {
  RouteHandle handle = WsRouter._routers[name];
  if (handle == null) {
   print(" Route does not exist ");
   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 Connect 
 IOWebSocketChannel webSocketChannel;

 factory WebSocket() => _webSocket();

 static WebSocket _instance;

 //  Constructor 
 WebSocket._() {
  //  Initialization webSocket Route 
  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 {
  //  For example, the server returns something like this 1 A json
  // {"cmd":"kick","data":{}}
  // {"cmd":"login","data":{}}
  Map params = json.decode(response);
  wsRouter.handle(params["cmd"], params["data"]);
 }

 onError(err) async {}

 onDone() async {}
}


Related articles: