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),
      ),
    );
  }
}
相关推荐
不会写代码0001 小时前
Flutter 框架跨平台鸿蒙开发 - 全国景区门票查询应用开发教程
flutter·华为·harmonyos
LaoZhangGong1231 小时前
学习TCP/IP的第3步:和SYN相关的数据包
stm32·单片机·网络协议·tcp/ip·以太网
kirk_wang2 小时前
Flutter艺术探索-Riverpod深度解析:新一代状态管理方案
flutter·移动开发·flutter教程·移动开发教程
猛扇赵四那边好嘴.2 小时前
Flutter 框架跨平台鸿蒙开发 - 旅行规划助手应用开发教程
flutter·华为·harmonyos
白狐_7983 小时前
【计网全栈通关】第 5 篇:网络层核心计算——IP 地址规划、子网划分与 CIDR
网络协议·tcp/ip·php
极安代理3 小时前
HTTP代理是什么?作用与场景全面解析
网络·网络协议·http
白狐_7985 小时前
【计网全栈通关】第 3 篇:链路层核心——封装成帧、CRC 校验与滑动窗口协议
网络·网络协议
2501_944424125 小时前
Flutter for OpenHarmony游戏集合App实战之俄罗斯方块七种形状
android·开发语言·flutter·游戏·harmonyos
CheungChunChiu6 小时前
Flutter 在嵌入式开发的策略与生态
linux·flutter·opengl
小白阿龙7 小时前
鸿蒙+flutter 跨平台开发——汇率查询器开发实战
flutter·华为·harmonyos·鸿蒙