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),
      ),
    );
  }
}
相关推荐
to future_37 分钟前
传输层协议UDP,TCP
网络·网络协议·tcp/ip·udp
bdawn7 小时前
深度集成DeepSeek大模型:WebSocket流式聊天实现
python·websocket·openai·api·实时聊天·deepseek大模型·流式输出
卷心菜不卷Iris9 小时前
第1章大型互联网公司的基础架构——1.3 HTTP-DNS
网络·网络协议·http·dns·互联网大厂·http-dns·基础架构
恋猫de小郭10 小时前
Flutter 正在推进全新 PlatformView 实现 HCPP, 它又用到了 Android 上的什么黑科技
android·科技·flutter
老赵骑摩托12 小时前
深入浅出gRPC:原理、HTTP/2协议与四种通信模式详解
网络·网络协议
Black蜡笔小新12 小时前
从中心化到点对点:视频通话SDK组件EasyRTC如何通过WebP2P技术实现低延迟通信
网络协议·音视频·p2p
帅次12 小时前
Flutter 异步编程利器:Future 与 Stream 深度解析
android·flutter·ios·小程序·kotlin·webview·android-studio
柯木超12 小时前
深入解析 Flutter Widget 树与布局:从电商首页到性能优化
flutter
浩浩测试一下14 小时前
TCP/UDP协议与OSI七层模型的关系解析| HTTPS与HTTP安全性深度思考》
网络协议·web安全·http·网络安全·https·可信计算技术·安全架构
李小轰_Rex14 小时前
现有Flutter项目适配鸿蒙:探索跨平台开发的无限可能
前端·flutter·harmonyos