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),
      ),
    );
  }
}
相关推荐
Zguigo1 小时前
lesson43-44深入理解 TCP 可靠传输与流量控制:从机制到实战
网络·网络协议·tcp/ip
不灭的程序员阿澄1 小时前
Nginx 容器化部署实战:SPA 路由、Cookie 透传与 WebSocket 全配置详解
websocket·nginx·状态模式
xcyxiner3 小时前
flutter 运行到模拟器上
android·前端·flutter
末代iOS程序员华仔3 小时前
iOS 语聊直播/聊天APP4.3条例被拒解决
flutter·ios·swift
恋猫de小郭4 小时前
Dart 3.13 的到底改了什么?为什么很重要?有什么坑?
android·前端·flutter
SendTomo4 小时前
基于WebRTC的P2P文件传输IP暴露是正常现象
网络·网络协议·tcp/ip·webrtc·p2p
熊IT4 小时前
HTTP 代理检测工具:快速检查代理可用性、出口 IP 与延迟
网络协议·tcp/ip·http
今儿敲了吗5 小时前
CN——HTTP 工作流程
网络·网络协议·http
酒神dnspup15 小时前
CDN 回源检测怎么做?用 DNSPup 验证节点命中、源站暴露与多地可用性
运维·服务器·网络·网络协议·tcp/ip