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),
      ),
    );
  }
}
相关推荐
幼儿园蛋小黄1 小时前
基于 TCP 的嵌入式网络通信学习总结
网络协议·学习·tcp/ip
木井巳2 小时前
【网络原理】TCP/IP 协议栈
网络·网络协议·tcp/ip·udp
++==2 小时前
RPC:grpc的使用与安装、server和client的使用示例、lsb_relese、自定制协议(LVC)+protobuf的RPC调用框架的实现
网络·网络协议·rpc
青瓦梦滋3 小时前
NAT技术
linux·服务器·网络·网络协议·tcp/ip
G佳伟4 小时前
宝塔面板打不开且 Bt-Panel 未运行:从 HTTP 502 到 gevent 缺失的完整排查与修复
网络协议·http·php
tbit4 小时前
Android Google Map PlatformView 图层异常排查与修复
flutter
哈__4 小时前
Flutter 3.44.9 + OpenHarmony7:home_widget 三方库桌面服务卡片(FormKit)的应用
flutter·华为·harmonyos
keyipatience4 小时前
IP网络层
服务器·网络·网络协议·ubuntu·http
白狐_7984 小时前
408 计算机网络|HTTP 的 RTT 怎么数:用多道题讲清楚
网络协议·计算机网络·http
Discipline~Hai4 小时前
Linux网络编程03-HTTP协议
linux·运维·服务器·网络·网络协议·http·linux网络编程