封装 websocekt util 类,添加websocket支持

hmxc
张萌 3 years ago
parent d2bcd5dc36
commit 5183b0623b

@ -0,0 +1,194 @@
import 'dart:async';
import 'package:bot_toast/bot_toast.dart';
import 'package:power_logger/power_logger.dart';
import 'package:web_socket_channel/io.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
const String baseUri = 'wss://test.kaidalai.cn/websocket';
enum SOCKETSTATUS {
CONNECTED, //
BREAKOFF, //
CLOSED, //
}
class WebSocketUtil {
static final WebSocketUtil _socket = WebSocketUtil._();
//
WebSocketUtil._();
//
factory WebSocketUtil() => _socket;
IOWebSocketChannel? _webSocket;
///
String user = 'admin';
///
SOCKETSTATUS _socketStatus = SOCKETSTATUS.CLOSED;
///
Timer? _heartTimer;
///
Duration _heartDuration = Duration(seconds: 30);
///
int _reconnectCount = 0;
///
int _reconnectTimes = 30;
///
Timer? _reconnectTimer;
///
Function(dynamic e)? onError;
///
Function? onStart;
///
Function(String message)? onReceiveMes;
///
Function? onClosed;
///websocket
void initWebSocket(
{Duration? heartDuration,
Function? onStart,
Function(String message)? onReceiveMes,
Function? onClosed,
Function(dynamic e)? onError}) {
this.onStart = onStart;
this.onReceiveMes = onReceiveMes;
this.onClosed = onClosed;
this.onError = onError;
if (heartDuration != null) {
this._heartDuration = heartDuration;
}
print('——————————webSocket init ——————————');
}
///
void setUser(String user) {
this.user = user;
}
///websocket
void startWebSocket() {
closeWebSocket();
try {
_webSocket = IOWebSocketChannel.connect(Uri.parse('$baseUri/$user'));
print('webSocket已连接服务器$baseUri/$user');
_socketStatus = SOCKETSTATUS.CONNECTED;
endReconnect();
onStart?.call();
_webSocket!.stream.listen(
(event) => webSocketReceiveMessage(event as String),
onError: webSocketOnError,
onDone: webSocketClosed);
initHeartBeat();
} catch (e) {
BotToast.showText(text: 'webSocket连接失败');
onError?.call(e);
LoggerData.addData(e);
}
}
//
webSocketReceiveMessage(message) {
if (message == '心跳正常') {
print('心跳正常————————${DateTime.now()}');
} else {
onReceiveMes?.call(message);
}
}
//
webSocketClosed() {
closeWebSocket();
onClosed?.call();
}
//
webSocketOnError(e) {
WebSocketChannelException ex = e;
_socketStatus = SOCKETSTATUS.BREAKOFF;
onError?.call(ex.message);
print('——————连接断开,开始重连');
startReconnect();
}
//
void startReconnect() {
endReconnect();
_reconnectTimer = Timer.periodic(Duration(milliseconds: 5000), (timer) {
_reconnectCount++;
print('——————第${_reconnectCount}次重连');
startWebSocket();
if (_reconnectCount >= _reconnectTimes) {
print('——————重连失败');
closeWebSocket();
}
});
}
//
void endReconnect() {
_reconnectTimer?.cancel();
_reconnectTimer = null;
_reconnectCount = 0;
}
///
void initHeartBeat() {
destoryHeart();
_heartTimer = Timer.periodic(_heartDuration, (timer) {
sentHeart();
});
}
//
void sentHeart() {
sendMessage('heartbeat');
}
///
void destoryHeart() {
_heartTimer?.cancel();
_heartTimer = null;
}
///
///websocket
void closeWebSocket() {
if (_webSocket != null) {
_webSocket!.sink.close();
print('——————websocket连接已关闭');
}
endReconnect();
destoryHeart();
_socketStatus = SOCKETSTATUS.CLOSED;
}
///websocket
void sendMessage(message) {
if (_webSocket != null) {
switch (_socketStatus) {
case SOCKETSTATUS.CONNECTED:
print('发送中:' + message);
_webSocket!.sink.add(message);
break;
case SOCKETSTATUS.CLOSED:
print('连接已关闭');
break;
case SOCKETSTATUS.BREAKOFF:
print('发送失败');
break;
default:
break;
}
}
}
}
Loading…
Cancel
Save