再开发过程中我们经常会使用到WebSocket,而插件库为我们提供了一个使用非常方便的插件
web_socket_channel
我们需要根据自己的Flutter 版本选择对应的即可
web_socket_channel: ^1.1.0
在pubspec.yaml中我们引入,然后pub get 一下
pub get
到此就完成插件的引用。下面就是使用了
官网的代码使用
import 'package:web_socket_channel/web_socket_channel.dart';
import 'package:web_socket_channel/status.dart' as status;
main() async {
var channel = IOWebSocketChannel.connect(Uri.parse('ws://localhost:1234'));
channel.stream.listen((message) {
channel.sink.add('received!');
channel.sink.close(status.goingAway);
});
}
下面是我对其进行了简单的封装
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:jianfa/view/main/my/message/detail/MessageDetailSocket.dart';
import 'package:jianfa/widget/CustomDialog.dart';
import 'package:web_socket_channel/io.dart';
import 'package:flutter/material.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
class WebSocketChannel {
// 创建WebSocketChannel 单利,全局只有一个对象
WebSocketChannel._privateConstructor();
static final WebSocketChannel _instance =
WebSocketChannel._privateConstructor();
static WebSocketChannel get instance {
return _instance;
}
BuildContext contexts;
IOWebSocketChannel channel;
// 开始进行链接
void connect(BuildContext context) {
contexts = context;
channel = IOWebSocketChannel.connect(
"ws://localhost:1234");
sendMessage();
channel.stream.listen(this.onData, one rror: one rror, onDone: onDone);
}
// 发送消息
void sendMessage() {
channel.sink.add("");
}
// 断连,然后执行重连
onDone() {
debugPrint("Socket is closed");
channel = IOWebSocketChannel.connect(
"ws://localhost:1234");
channel.stream.listen(this.onData, one rror: one rror, onDone: onDone);
(() async {});
}
// 错误日志
one rror(err) {
debugPrint(err.runtimeType.toString());
WebSocketChannelException ex = err;
debugPrint(ex.message);
}
// 接受数据,数据json字符串,然后转成Map
onData(event) {
print('收到消息:' + event);
Map<String, dynamic> map = json.decode(event);
}
void dispose() {
channel.sink.close();
}
}
下面是使用
// 创建对象
WebSocketChannel webSocketChannel = WebSocketChannel.instance;
// 开始进行链接
webSocketChannel.connect(context);
// 断开链接
webSocketChannel.dispose();
到此就完成了web_socket_channel的简单封装和基本使用。