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),
      ),
    );
  }
}
相关推荐
周淳APP13 分钟前
【HTTP之跨域请求以及Cookie携带的限制】
前端·网络·网络协议·http
周淳APP32 分钟前
【HTTP相关及RESTful】风萧萧兮易水寒之壮士学习不复返
前端·javascript·网络·网络协议·http·restful·jsonp
萝卜白菜。32 分钟前
http头Location是相对路径还是绝对路径
网络·网络协议·http
格鸰爱童话32 分钟前
springboot实现websocket在线聊天室
spring boot·后端·websocket
周淳APP37 分钟前
【计算机网络之HTTP、TCP、UDP、HTTPS、Socket网络连接】
前端·javascript·网络·网络协议·http·前端框架
博语小屋37 分钟前
HTTP详解
网络·网络协议·http
汤愈韬1 小时前
各类LSA的解析(一二三类LSA)
网络·网络协议·网络安全·security
Initialize-le5 小时前
WMware桥接模式配置静态IP上网
网络协议·tcp/ip·桥接模式
啥都想学点6 小时前
第12天:flutter中的自定义类的介绍
flutter
yangzheui8 小时前
使用vscode开发flutter项目环境配置
ide·vscode·flutter