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),
      ),
    );
  }
}
相关推荐
消失的旧时光-194326 分钟前
Flutter 插件通信架构设计:从 Channel 到 FFI 的完整边界
flutter·ffi
liwulin05061 小时前
【JAVA】创建一个不需要依赖的websocket服务器接收音频文件
java·服务器·websocket
ICT系统集成阿祥1 小时前
OSPF邻居建立失败完整排查指南
网络·网络协议
liulilittle2 小时前
OPENPPP2 Code Analysis One
网络·c++·网络协议·信息与通信·通信
用户372824860223 小时前
TCP 连接状态详解
网络协议
郑梓斌4 小时前
Luban 2 Flutter:一行代码在 Flutter 开发中实现图片压缩功能
flutter·ios
哈__5 小时前
Flutter 开发鸿蒙 PC 第一个应用:窗口创建 + 大屏布局
flutter·华为·harmonyos
AiFlutter5 小时前
蓝牙调试助手开发(03):概要设计
flutter·低代码平台·aiflutter·aiflutter低代码·flutter低代码开发·蓝牙调试·蓝牙调试助手
mangge085 小时前
ESP8266 温湿度监测系统教程(SHT30+MAX7219+LeanCloud+HTTP 服务)
网络·网络协议·http
阿巴~阿巴~5 小时前
“可达”方能“可靠”:深入解析网络层在TCP通信中的基石作用
运维·服务器·网络·网络协议·tcp/ip·ip·tcp