锁屏自动重连websocket
import 'package:flutter/foundation.dart';
import 'package:web_socket_channel/io.dart';
import 'package:flutter/material.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final title = '192';
return MaterialApp(
title: title,
home: MyHomePage(
title: title,
channel: IOWebSocketChannel.connect('ws://192.168.3.4:8088/echo'),
),
);
}
}
class MyHomePage extends StatefulWidget {
final String title;
String backendData = '';
WebSocketChannel channel;
MyHomePage({Key key, @required this.title, @required this.channel})
: super(key: key);
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
TextEditingController _controller = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Form(
child: TextFormField(
controller: _controller,
decoration: InputDecoration(labelText: 'Send a message'),
),
),
Text(widget.backendData),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _sendMessage,
tooltip: 'Send message',
child: Icon(Icons.send),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
void _sendMessage() {
if (_controller.text.isNotEmpty) {
widget.channel.sink.add(_controller.text);
// super.initState();
widget.channel.stream.listen(this.onData, onError: onError, onDone: onDone);
(() async {
setState(() {
// widget.backendData=this.onData;
});
});
}
}
onDone(){
debugPrint("Socket is closed");
widget.channel=IOWebSocketChannel.connect('ws://192.168.3.4:8088/echo');
this._sendMessage();
}
onError(err){
debugPrint(err.runtimeType.toString());
WebSocketChannelException ex = err;
debugPrint(ex.message);
}
onData(event){
setState(() {
widget.backendData=event;
});
// debugPrint(event);
// widget.backendData=event;
}
@override
void dispose() {
widget.channel.sink.close();
super.dispose();
}
}
网友评论