Flutter WebSocket简单例子

引入插件 :web_socket_channel: ^3.0.1

使用如下代码:

Dart 复制代码
class _MyHomePageState extends State<MyHomePage> {
  String text = "";
  var textController = TextEditingController();
  late IOWebSocketChannel channel;

  void _incrementCounter() {
    channel.sink.add(textController.text);
    textController.text = "";
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    HttpClient httpClient = HttpClient();

    /// 解决证书问题
    httpClient.badCertificateCallback = (X509Certificate cert, String host, int port) {
      // String PEM = "XXXXXX";// 证书信息
      // if(cert.pem == PEM){
      //   return true;// 正式一致,则允许发送数据
      // }
      // return false;

      /// 这里可写死true
      return true;
    };
    channel = IOWebSocketChannel.connect(Uri.parse('ws://echo.websocket.org'), customClient: httpClient);
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text("WebSocket例子"),
      ),
      body: StreamBuilder(
          stream: channel.stream,
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.active) {
              text = "${snapshot.data}";
            } else if (snapshot.connectionState == ConnectionState.done) {
              text = "已断开连接,断开原因:${snapshot.error}";
            } else if (snapshot.connectionState == ConnectionState.waiting) {
              text = "连接中";
            } else {
              text = "...";
            }
            return Column(
              children: [
                Text(text),
                TextField(
                  controller: textController,
                ),
                TextButton(
                    onPressed: () {
                      channel.sink.close();
                    },
                    child: const Text("断开")),
                TextButton(
                    onPressed: () {
                      setState(() {});
                    },
                    child: const Text("重连")),
              ],
            );
          }),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}
相关推荐
最强小杰6 小时前
minimax-m3 突然报 HTTP 529 怎么办?连续重试为何更难恢复,退避时间该怎么算?
网络·网络协议·http·ai
m0_639906947 小时前
TCP与UDP协议详解|原理、区别、粘包拆包、应用场景,面试总
网络协议·tcp/ip·udp
QianhangQianping9 小时前
WebSocket实时推送+ HTTP 定时轮询:一块大屏两套取数怎么不打架
前端·websocket·网络协议·http·低代码·架构·数据可视化
车载中间件通信10 小时前
[TC8测试]TCP_FLAGS_INVALID_13_Flag SYN,ACK
网络·网络协议·tcp/ip
车载中间件通信10 小时前
[TC8测试]TCP_FLAGS_PROCESSING_06
数据库·网络协议·tcp/ip·中间件·tc8
恋猫de小郭11 小时前
感人,Flutter 居然有了一个超实用提案,期待落地
android·前端·flutter
李纲明12 小时前
WordPress 全站 HTTPS 后仍显示「不安全」或锁被划掉:先清混合内容,再核证书链与强制跳转
网络协议·安全·https·wordpress·devdiy·混合内容
尹人入圣1 天前
目前热门的IP驱动产业新场景新工具
网络·python·网络协议·tcp/ip
好的佩奇1 天前
Dart 之增强枚举
android·flutter·dart
好的佩奇1 天前
蓝牙之无线电与通信距离
android·flutter·蓝牙