【问题标题】:Debugging web-socket issues in Flutter在 Flutter 中调试 web-socket 问题
【发布时间】:2020-05-12 01:39:53
【问题描述】:

我想知道如何在 Flutter 中调试 web-socket 连接问题。

从 Flutter 文档中举出最简单的例子:
https://flutter.dev/docs/cookbook/networking/web-sockets#complete-example

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 = 'WebSocket Demo';
    return MaterialApp(
      title: title,
      home: MyHomePage(
        title: title,
        channel: IOWebSocketChannel.connect('ws://echo.websocket.org'),
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  final String title;
  final 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'),
              ),
            ),
            StreamBuilder(
              stream: widget.channel.stream,
              builder: (context, snapshot) {
                return Padding(
                  padding: const EdgeInsets.symmetric(vertical: 24.0),
                  child: Text(snapshot.hasData ? '${snapshot.data}' : ''),
                );
              },
            )
          ],
        ),
      ),
      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);
    }
  }

  @override
  void dispose() {
    widget.channel.sink.close();
    super.dispose();
  }
}

此代码运行顺利。

但是,如果我为套接字服务器添加了一些乱码(例如IOWebSocketChannel.connect('ws://total-gibberish-clearly-not-a-ws-server')),代码仍然可以毫无怨言地运行。 显然发送的消息没有回显(这是 'ws://echo.websocket.org' 服务器所做的),但没有错误消息,没有迹象表明这不是 web-socket 服务器。

我的实际情况是我确实有一个真正的 web-socket 服务器,但我无法连接到它,但我不知道问题是什么。

如何在 Flutter 中检测并显示失败的 web-socket 连接的错误详情?

【问题讨论】:

    标签: flutter dart websocket


    【解决方案1】:

    我在这个示例套接字客户端中使用了不同的(更底层的)方法:https://github.com/krisrandall/really_simple_socket_client
    但它包括错误检测。

    这是所有代码:

    import 'dart:io';
    
    WebSocket _webSocket;
    
    String socketServerUrl = 'ws://echo.websocket.org/';
    //String socketServerUrl = 'ws://echo.FAILS.org/';
    
    void main() {
    
      Future<WebSocket> futureWebSocket = WebSocket.connect(socketServerUrl);
      futureWebSocket.then((WebSocket ws) {
        _webSocket = ws;
        print(_webSocket.readyState);
    
        _webSocket.listen(
            (d) { print(d); },
            onError: (e) { print("error"); print(e); }, 
            onDone: () => print("done")
        );
    
        // send message
        _webSocket.add('hello websocket world');
    
      });
    
    
    }
    

    【讨论】: