除了正常的HTTP请求外,我们还可以使用WebSocket连接到服务器。WebSocket允许与服务器进行双向通信而无需轮询。

在这个例子中,我们将连接到由websocket.org提供的测试服务器。服务器将简单地返回我们发送给它的相同消息!

步骤

  1. 连接到WebSocket服务器。
  2. 监听来自服务器的消息。
  3. 将数据发送到服务器。
  4. 关闭WebSocket连接。

1. 连接到WebSocket服务器

web_socket_channel package 提供了我们需要连接到WebSocket服务器的工具.

该package提供了一个WebSocketChannel允许我们既可以监听来自服务器的消息,又可以将消息发送到服务器的方法。

在Flutter中,我们可以创建一个WebSocketChannel连接到一台服务器:

  1. final channel = new IOWebSocketChannel.connect('ws://echo.websocket.org');

2. 监听来自服务器的消息

现在我们建立了连接,我们可以监听来自服务器的消息,在我们发送消息给测试服务器之后,它会返回相同的消息。

我们如何收取消息并显示它们?在这个例子中,我们将使用一个StreamBuilder Widget来监听新消息, 并用一个Text Widget来显示它们。

  1. new StreamBuilder(
  2. stream: widget.channel.stream,
  3. builder: (context, snapshot) {
  4. return new Text(snapshot.hasData ? '${snapshot.data}' : '');
  5. },
  6. );

这是如何工作的?

WebSocketChannel提供了一个来自服务器的消息Stream 。

Stream类是dart:async包中的一个基础类。它提供了一种方法来监听来自数据源的异步事件。与Future返回单个异步响应不同,Stream类可以随着时间推移传递很多事件。

StreamBuilder Widget将连接到一个Stream, 并在每次收到消息时通知Flutter重新构建界面。

3. 将数据发送到服务器

为了将数据发送到服务器,我们会add消息给WebSocketChannel提供的sink。

  1. channel.sink.add('Hello!');

这是如何工作的?

WebSocketChannel提供了一个StreamSink,它将消息发给服务器。

StreamSink类提供了给数据源同步或异步添加事件的一般方法。

4. 关闭WebSocket连接

在我们使用WebSocket后,要关闭连接:

  1. channel.sink.close();

完整的例子

  1. import 'package:flutter/foundation.dart';
  2. import 'package:web_socket_channel/io.dart';
  3. import 'package:flutter/material.dart';
  4. import 'package:web_socket_channel/web_socket_channel.dart';
  5. void main() => runApp(new MyApp());
  6. class MyApp extends StatelessWidget {
  7. @override
  8. Widget build(BuildContext context) {
  9. final title = 'WebSocket Demo';
  10. return new MaterialApp(
  11. title: title,
  12. home: new MyHomePage(
  13. title: title,
  14. channel: new IOWebSocketChannel.connect('ws://echo.websocket.org'),
  15. ),
  16. );
  17. }
  18. }
  19. class MyHomePage extends StatefulWidget {
  20. final String title;
  21. final WebSocketChannel channel;
  22. MyHomePage({Key key, @required this.title, @required this.channel})
  23. : super(key: key);
  24. @override
  25. _MyHomePageState createState() => new _MyHomePageState();
  26. }
  27. class _MyHomePageState extends State<MyHomePage> {
  28. TextEditingController _controller = new TextEditingController();
  29. @override
  30. Widget build(BuildContext context) {
  31. return new Scaffold(
  32. appBar: new AppBar(
  33. title: new Text(widget.title),
  34. ),
  35. body: new Padding(
  36. padding: const EdgeInsets.all(20.0),
  37. child: new Column(
  38. crossAxisAlignment: CrossAxisAlignment.start,
  39. children: <Widget>[
  40. new Form(
  41. child: new TextFormField(
  42. controller: _controller,
  43. decoration: new InputDecoration(labelText: 'Send a message'),
  44. ),
  45. ),
  46. new StreamBuilder(
  47. stream: widget.channel.stream,
  48. builder: (context, snapshot) {
  49. return new Padding(
  50. padding: const EdgeInsets.symmetric(vertical: 24.0),
  51. child: new Text(snapshot.hasData ? '${snapshot.data}' : ''),
  52. );
  53. },
  54. )
  55. ],
  56. ),
  57. ),
  58. floatingActionButton: new FloatingActionButton(
  59. onPressed: _sendMessage,
  60. tooltip: 'Send message',
  61. child: new Icon(Icons.send),
  62. ), // This trailing comma makes auto-formatting nicer for build methods.
  63. );
  64. }
  65. void _sendMessage() {
  66. if (_controller.text.isNotEmpty) {
  67. widget.channel.sink.add(_controller.text);
  68. }
  69. }
  70. @override
  71. void dispose() {
  72. widget.channel.sink.close();
  73. super.dispose();
  74. }
  75. }