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),
      ),
    );
  }
}
相关推荐
chen36739 小时前
[Comake][D1][AI_AO][bf_ssl_demo]
网络·网络协议·ssl
初听于你9 小时前
LoRa与ZigBee:物联网双雄对决
服务器·网络·windows·网络协议·计算机网络
初遇你时动了情10 小时前
uniapp/flutter中实现苹果IOS 26 毛玻璃效果、跟随滑动放大动画
flutter·ios·uni-app
笨蛋不要掉眼泪13 小时前
deepseek封装结合websocket实现与ai对话
人工智能·websocket·网络协议
listhi52014 小时前
Vue.js 3的组合式API
android·vue.js·flutter
起风了___14 小时前
Flutter 多端音频控制台:基于 audio_service 实现 iOS、Android 锁屏与通知中心播放控制
前端·flutter
小李独爱秋16 小时前
计算机网络经典问题透视:当路由器需要同时连接以太网和ATM网络时,需要添加什么硬件?
运维·网络协议·计算机网络·网络安全·智能路由器
leinchu17 小时前
Flutter + Codebuddy的坑
flutter
一瓢一瓢的饮 alanchan18 小时前
HTTPS接口国密安全设计-示例
网络协议·安全·https·国密 国家商用密码·数字签名 数字证书·sm2 sm4 sm3·对称加密 非对称加密