Implementation of custom websocket routing in fluent


After the server pushes data to the client in the fluent websocket, many people’s processing is if / switch. I feel that this writing method is not good!

One way of thinking:

Create a new socket directory in the Lib directory and create two files in it main.dart and router.dart ;
main.dart : it mainly controls the disconnection of websocket and the processing of received messages;
router.dart The message returned by websocket server is routed;


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;

 Future<void> handle(String name, Map params) async {
  RouteHandle handle = WsRouter._routers[name];
  if (handle == null) {
   Print ("route does not exist");

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


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

var webSocket = new WebSocket();

class WebSocket {
 //Websocket connection
 IOWebSocketChannel webSocketChannel;

 factory WebSocket() => _webSocket();

 static WebSocket _instance;

 WebSocket._() {
  //Initialize websocket routing

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

 conn() {
  IOWebSocketChannel channel = new IOWebSocketChannel.connect(
    pingInterval: Duration(milliseconds: 100));
    .listen((data) => onMessage(data), onError: onError, onDone: onDone);

  this.webSocketChannel = channel;

 onMessage(response) async {
  //For example, the server returns a JSON like this
  // {"cmd":"kick","data":{}}
  // {"cmd":"login","data":{}}
  Map params = json.decode(response);
  wsRouter.handle(params["cmd"], params["data"]);

 onError(err) async {}

 onDone() async {}

The above is the whole content of this article. I hope it will help you in your study, and I hope you can support developepaer more.

Recommended Today

mcmnhdlr.exe What process can be deleted? Mcmnhdl process query

Process file: mcmnhdl or mcmnhdlr.exeProcess name: vsocecktaskProcess category: processes with security risksEnglish Description: mcmnhdlr.exe is vital process for McAfee SecurityCenter and Virusscan Online. Removing this process will dissable the automatic scanning. Chinese reference:mcmnhdlr.exe It is related to McAfee security center.Produced by: network associates, IncOf McAfee VirusScanSystem process: noBackground program: YesNetwork related: noCommon error: n / […]