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),
      ),
    );
  }
}
相关推荐
王亚博_Abel4 小时前
域名是怎么变成 IP 的?手拆 DNS 解析四个实验实测
网络·网络协议·tcp/ip
用户84913717547164 小时前
两版 SNMP 报文只差 1 个字节,我盯了半天才看懂问题出在哪
网络协议
AndreaYYmm5 小时前
SIGUSR2 触发热重载:一个正在抓包的进程如何原子地换掉规则集
c语言·网络协议
用户849137175471610 小时前
为什么 SNMP 叫"简单"?真相是:设备少干活,复杂全甩给了你
网络协议
白小飞不会飞11 小时前
【AUTOSAR】CP SOME/IP-TP
c++·嵌入式硬件·网络协议·车载系统·autosar
神一样的老师11 小时前
用 FCU1501 双网口打通两个不同网段:IP 转发 + NAT 实战
网络·网络协议·tcp/ip
恋猫de小郭12 小时前
站起来,Flutter 要支持真正的 3D Texture 了
android·前端·flutter
keepquietl1 天前
UDS on CAN 入门(6):诊断响应要等多久?读懂 P2、P2* 和 S3
网络·网络协议
YIAN1 天前
流式 TTS 和普通TTS到底有什么区别?一个文档教会你!
前端·websocket·node.js
黑科技iOS上架1 天前
iOS4.3合规自测手段:二进制分析
flutter·ios·cocoa·审核