Flutter WebSocket简单例子

引入插件 :web_socket_channel: ^3.0.1

使用如下代码:

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),
      ),
    );
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值