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),
      ),
    );
  }
}
相关推荐
三体世界2 小时前
TCP传输控制层协议深入理解
linux·服务器·开发语言·网络·c++·网络协议·tcp/ip
LuDvei2 小时前
CH9121T电路及配置详解
服务器·嵌入式硬件·物联网·网络协议·tcp/ip·网络安全·信号处理
火柴就是我4 小时前
每日见闻之Container Decoration
android·flutter
令狐掌门4 小时前
tcp长连接与短连接
网络·网络协议·tcp/ip
创小匠4 小时前
创客匠人洞察:AI 时代创始人 IP 打造如何突破效率与价值的平衡
人工智能·网络协议·tcp/ip
zhysunny5 小时前
WebSocket实战:实现实时聊天应用 - 双向通信技术详解
网络·websocket·网络协议
hrrrrb5 小时前
【TCP/IP】5. IP 协议
网络协议·tcp/ip·php
hhh123987_6 小时前
以太网基础⑤UDP 协议原理与 FPGA 实现
网络·网络协议·udp
灰海6 小时前
封装WebSocket
前端·网络·websocket·网络协议·vue
DemonAvenger6 小时前
实现可靠的 UDP 协议:Go 语言版本
网络协议·架构·go