callWebSocket method

void callWebSocket()

Implementation

void callWebSocket() async {
  final int rd = _randomNumber(1000000, 9999999);
  final int dt = DateTime.now().millisecondsSinceEpoch;
  final String urlStr =
      '$baseUrl?cert=$cert&token=$token&userid=$userId&custom=$custom&ty=${getClientType()}&sign=$sign&rd=$rd&dt=$dt';
  try {
    _websocket = IOWebSocketChannel.connect(Uri.parse(urlStr));
    // 超时时间设置
    // 网络相关的不需要
    // 多少秒可以根据情况配置
    await _websocket?.ready.timeout(Duration(seconds: 10));
  }catch (e){
    print("ChatLib: 初始化WebSocket时发生异常: $e");
    String errorMsg = "连接初始化失败";

    if (e is FormatException) {
      errorMsg = "WebSocket URL格式错误";
    } else if (e is ArgumentError) {
      errorMsg = "WebSocket参数错误";
    }

    _disConnected(Code: 1008, msg: errorMsg);
    return;
  }
  print("wss地址:" + urlStr);

  _websocket?.stream.listen(
        (data) {
      //print("ChatLib: received message: $message");
      if (data.length == 1) {
        if (data[0] == 0) {
          print("ChatLib:收到心跳回执${_beatTimes}  at ${DateTime.now()}\n");
        } else if (data[0] == 1) {
          print("ChatLib:在别处登录了");
          _disConnected(Code: 1010, msg: "在别处登录了");
        } else if (data[0] == 2) {
          _disConnected(Code: 1002, msg: "无效的Token");
          print("ChatLib:无效的Token");
        } else if (data[0] == 3) {
          print("ChatLib:收到1字节回执 3");
        } else {
          print("ChatLib:收到1字节回执");
        }
      } else {
        print("收到socket数据 at ${DateTime.now()}");
        //收到socket数据,表明用户正在活跃,闲置时间重置
        resetSessionTime();
        var payLoad = Payload.fromBuffer(data);
        if (payLoad.act == Action.ActionSCRecvMsg) {
          var scMsg = SCRecvMessage.fromBuffer(payLoad.data);
          if (scMsg.msg != null) {
            if (scMsg.msg.msgOp == MessageOperate.MSG_OP_DELETE) {
              delegate?.msgDeleted(scMsg.msg, payLoad.id, null);
            } else {
              delegate?.receivedMsg(scMsg.msg);
            }
          }
        } else if (payLoad.act == Action.ActionSCHi) {
          var msg = SCHi.fromBuffer(payLoad.data);
          payloadId = payLoad.id;
          delegate?.connected(msg);
          isConnected = true;
          _startTimer();
        } else if (payLoad.act == Action.ActionSCWorkerChanged) {
          var msg = SCWorkerChanged.fromBuffer(payLoad.data);
          if (msg != null) {
            consultId = msg.consultId;
            delegate?.workChanged(msg);
          }
        } else if (payLoad.act == Action.ActionSCDeleteMsgACK) {
          var msg = SCReadMessage.fromBuffer(payLoad.data);
          if (msg != null) {
            var cMsg = Message();
            cMsg.msgId = msg.msgId;
            cMsg.msgOp = MessageOperate.MSG_OP_DELETE;
            cMsg.chatId = msg.chatId;
            delegate?.msgDeleted(cMsg, payLoad.id, null);
          }
        } else if (payLoad.act == Action.ActionCSDeleteMsg) {
          var msg = CSRecvMessage.fromBuffer(payLoad.data);
          if (msg != null) {
            var cMsg = Message();
            cMsg.msgId = msg.msgId;
            cMsg.msgOp = MessageOperate.MSG_OP_DELETE;
            cMsg.chatId = msg.chatId;
            delegate?.msgDeleted(cMsg, payLoad.id, null);
          }
        } else if (payLoad.act == Action.ActionForward) {
        } else if (payLoad.act == Action.ActionSCSendMsgACK) {
          var msg = SCSendMessage.fromBuffer(payLoad.data);
          print("ChatLib:收到回执${payLoad.id}");
          if (msg != null) {
            var pId = payLoad.id;
            if (msgList[pId] != null) {
              var cMsg = msgList[pId];
              cMsg?.msgId = msg.msgId;
              cMsg?.msgTime = msg.msgTime;
              chatId = msg.chatId;

              if (cMsg != null) {
                if (sendingMsg?.msgOp == MessageOperate.MSG_OP_DELETE) {
                  cMsg.msgOp = MessageOperate.MSG_OP_DELETE;
                  print("ChatLib:删除消息成功");
                  delegate?.msgDeleted(cMsg, pId, msg.errMsg);
                } else if (msg.errMsg.isNotEmpty) {
                  cMsg.msgId = Int64(-2);
                }
                delegate?.msgReceipt(cMsg, pId, msg.errMsg);
              }
            }
          }
        }
      }
    },
    onDone: () {
      // Handle when the WebSocket connection is closed.
      print("ChatLib: WebSocket connection closed.");
      // You can trigger a reconnection attempt or clean up resources here.
      //reconnect();
      _disConnected();
    },
    onError: (error) {
      print("ChatLib: WebSocket error: $error");

      // 根据错误类型提供更具体的错误信息
      String errorMsg = "连接错误";
      int errorCode = 1001;

      if (error is SocketException) {
        if (error.message.contains("Failed host lookup")) {
          errorMsg = "无法解析服务器地址,请检查网络设置或DNS配置";
          errorCode = 1003;
        } else if (error.message.contains("Connection refused")) {
          errorMsg = "服务器拒绝连接";
          errorCode = 1004;
        } else if (error.message.contains("Connection timed out")) {
          errorMsg = "连接超时";
          errorCode = 1007;
        }
      }
      _disConnected(Code: errorCode, msg: errorMsg);
    },
    cancelOnError: true,
  );
}