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),
      ),
    );
  }
}
相关推荐
liulilittle23 分钟前
TCP UCP v1.0:当 BBRv1 遇上卡尔曼滤波
网络·网络协议·tcp/ip
哈撒Ki1 小时前
快速入门WebSocket
前端·websocket
小娄~~1 小时前
TCP/IP协议和TFTP协议
网络·网络协议·tcp/ip
xiaoxue..1 小时前
HTTPS:更安全的HTTP,从加密原理、数字证书到TLS 握手全解析
网络协议·面试·https
恋猫de小郭2 小时前
Flutter GenUI 0.9 和 A2UI 0.9 发布,全动动态 UI 支持,AI 在 App 里直出界面
android·flutter·ios
KKei16382 小时前
Flutter for OpenHarmony 学习专注模式APP技术文章
学习·flutter·华为·harmonyos
liulilittle2 小时前
TCP UCP v1.0 拥塞控制算法(Linux Kernel CC-A)
linux·网络·网络协议·tcp/ip·c·通信·拥塞控制
UnicornDev2 小时前
【Flutter x HarmonyOS 6】挑战功能的业务逻辑实现
flutter·华为·harmonyos·鸿蒙·鸿蒙系统
Lan_Se_Tian_Ma2 小时前
使用Cursor封装Flutter项目基建框架
前端·人工智能·flutter
天天开发2 小时前
Flutter Widget Previewer使用指南:提升开发效率的利器
前端·javascript·flutter