【Flutter】io库里自带的WebSocket使用
2020-08-20 本文已影响0人
在这蓝色天空下
import 'dart:io';
class LCWebSocketManager {
LCWebSocketManager._();
static LCWebSocketManager _manager;
factory LCWebSocketManager() {
if (_manager == null) {
_manager = LCWebSocketManager._();
}
return _manager;
}
WebSocket _webSocket;
initWebSocket({Function success, Function failure}) async {
var _linkAddress = "ws://62.234.***.***:5300?token=";
var token = "";
try {
_webSocket = await WebSocket.connect(_linkAddress + token);
print("【WebSocket】创建链接");
if (_webSocket.readyState == WebSocket.open) {
success();
_ping();
_webSocket.listen((onData) {
print("【WebSocket】接收到消息 == > $onData");
_chengaMessage(onData);
}, onError: (error) {
print("【WebSocket】错误 == > $error");
}, onDone: () {
print("【WebSocket】结束链接");
});
} else {
failure();
return;
}
} catch (e) {
failure();
return;
}
}
/// 发送心跳包
_ping() {
Future.delayed(Duration(seconds: 3)).then((value) {
if (_webSocket.readyState == WebSocket.open) {
_webSocket.add("hello, my name is lichuang!");
_ping();
}
});
}
/// 发送消息
sendMessage() {
_webSocket.add("hello, my name is lilei!");
}
/// 关闭
closeConnect() {
_webSocket.close();
}
/// 当前状态
currentState() {
switch (_webSocket.readyState) {
case WebSocket.connecting:
print('【WebSocket】当前状态 ==> connecting');
break;
case WebSocket.open:
print('【WebSocket】当前状态 ==> open');
break;
case WebSocket.closing:
print('【WebSocket】当前状态 ==> closing');
break;
case WebSocket.closed:
print('【WebSocket】当前状态 ==> closed');
break;
default:
}
}
/// 处理接收到的消息
_chengaMessage(dynamic data) {
var model = ReceiveMessageModel.fromJson(convert.jsonDecode(data));
if (model.type == 0) {
print("【WebSocket】消息消息");
TTSUtil().initTTS();
TTSUtil().speak(model.data.label);
} else if (model.type == 1) {
print("【WebSocket】我是心跳");
} else if (model.type == 2) {
print("【WebSocket】链接成功");
}
}
}
class ReceiveMessageModel {
int type;
ReceiveMessageDetailModel data;
ReceiveMessageModel.fromJson(Map<String, dynamic> json) {
type = json['type'];
data = ReceiveMessageDetailModel.fromJson(json['data']);
}
}
class ReceiveMessageDetailModel {
int id;
String label;
ReceiveMessageDetailModel.fromJson(Map<String, dynamic> json)
: id = json['id'],
label = json['label'];
}