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),
      ),
    );
  }
}
相关推荐
不做菜鸟的网工19 小时前
BGP特性
网络协议
stringwu2 天前
Flutter 开发必备:MVI 架构的高效实现指南
前端·flutter
程序员老刘3 天前
Flutter版本选择指南:3.44系列继续观望 | 2026年6月
flutter·ai编程·客户端
明月_清风3 天前
开发者网络概念全扫盲:一篇搞定
后端·网络协议
刘马想放假3 天前
Modbus 全栈技术解析:TCP、RTU、ASCII、RTU over TCP
数据结构·网络协议
王二端茶倒水4 天前
一套可落地的无线运营方案,不能只管 AP,还要管用户、计费和运维
网络协议
162723816084 天前
EtherCAT 分布式时钟(DC)原理与配置实战:把多轴真正"对齐到同一时刻"
网络协议
用户965597361904 天前
Provider vs Bloc vs GetX vs Riverpod:Flutter 状态管理方案怎么选?
flutter
恋猫de小郭4 天前
Flutter Patchwork,不用 Fork 改依赖包源码的第三方工具
android·前端·flutter
程序员老刘4 天前
跑分第一的编程大模型,我为啥不用?
flutter·ai编程·vibecoding