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),
      ),
    );
  }
}
相关推荐
带娃的IT创业者3 小时前
工具状态失踪之谜:EventBus事件漏接与asyncio.Lock并发陷阱双线诊断
qt·websocket·并发控制·eventbus·事件驱动架构·pwa·asyncio.lock
Predestination王瀞潞5 小时前
5.4.2 通信->WWW万维网内容访问标准(W3C):WWW(World Wide Web) 核心技术规范
网络·网络协议·https·www
虾..5 小时前
TCP协议
网络·网络协议·tcp/ip
上去我就QWER6 小时前
详解HTTP协议中的multipart/form-data
网络·网络协议·http
Predestination王瀞潞8 小时前
5.3.2 通信->HTTP3超文本传输协议标准(IETF RFC 9114):Headers 请求头 响应头
网络·网络协议·tcp/ip
sugar__salt8 小时前
网络原理(五)——HTTP
网络·网络协议·http
ljt27249606619 小时前
Flutter笔记--事件处理
笔记·flutter
夜泉_ly9 小时前
泉面 TOP150 -TCP 和 UDP 的区别?
网络协议·tcp/ip·udp
特立独行的猫a9 小时前
ESP32小智AI的WebSocket 调试工具实现,小智AI后台交互过程揭秘(一、开篇介绍 )
人工智能·websocket·网络协议·esp32·小智ai
Predestination王瀞潞10 小时前
5.4.1 通信->WWW万维网内容访问标准(W3C):WWW(World Wide Web)基本信息&核心设计目标&现实意义
css·网络·网络协议·html·url·www