图片一:
页面窗口
图片二:
输入内容,点击右下角发送,在输入框下面显示的是服务器返回的值
图片三:
再次输入内容,点击右下角发送,同样在输入框下面显示的是服务器返回的值
代码+注释:
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';
/**
连接到WebSocket服务器。
监听来自服务器的消息。
将数据发送到服务器。
关闭WebSocket连接。
*/
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final title = 'WebSocket Demo';
return new MaterialApp(
title: title,
home: new MyHomePage(
title: title,
/// 连接到WebSocket服务器
channel: new IOWebSocketChannel.connect('ws://echo.websocket.org'),
),
);
}
}
class MyHomePage extends StatefulWidget {
final String title;
final WebSocketChannel channel; // Web插口途径
MyHomePage({Key key, @required this.title, @required this.channel})
: super(key: key);
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
TextEditingController _controller = new TextEditingController();
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: new Padding(
padding: const EdgeInsets.all(20.0),
child: new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
new Form(
child: new TextFormField(
controller: _controller,
decoration: new InputDecoration(labelText: 'Send a message'),
),
),
/// 监听来自服务器的消息
/// Widget将连接到一个Stream, 并在每次收到消息时通知Flutter重新构建界面。
new StreamBuilder(
//该Stream类是dart:async包中的一个基础类。它提供了一种方法来监听来自数据源的异步事件。与Future返回单个异步响应不同,Stream类可以随着时间推移传递很多事件。
stream: widget.channel.stream,
builder: (context, snapshot) {
return new Padding(
padding: const EdgeInsets.symmetric(vertical: 24.0),
child: new Text(snapshot.hasData ? '${snapshot.data}' : ''),
);
},
)
],
),
),
floatingActionButton: new FloatingActionButton(
onPressed: _sendMessage,
tooltip: 'Send message',
child: new Icon(Icons.send),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
///将数据发送到服务器
void _sendMessage() {
if (_controller.text.isNotEmpty) { //只要文本框的值不为空
///为了将数据发送到服务器,我们会add消息给WebSocketChannel提供的sink。
widget.channel.sink.add(_controller.text);
}
}
@override
void dispose() {
/// 关闭WebSocket连接
widget.channel.sink.close();
super.dispose();
}
}
喜欢记得点个赞哟,我是王睿,很高兴认识大家!
更多原理请参考谷歌官网:使用WebSockets