gpt4 book ai didi

flutter - IOWebSocketChannel 检测连接何时打开

转载 作者:行者123 更新时间:2023-12-03 03:12:13 27 4
gpt4 key购买 nike

我是 Dart/flutter 的新手。我正在尝试使用 WebSocketChannel连接到 websocket 服务器。

有没有办法检测与服务器的连接何时完成?

我想要做的是在与服务器的连接完成时发送一些消息。

在 javascript 实现中,这是这样完成的:

exampleSocket.onopen = function (event) {
exampleSocket.send("Here's some text that the server is urgently awaiting!");
};

Dart/flutter 有替代方案吗?可以和 WebSocketChannel一起使用吗?

最佳答案

WebSocket
类静态方法 connect
返回建立连接时解析为 Web 套接字的 Future 。

如果您想在连接建立时发送消息,那么应该可以:

  import 'dart:io';
import 'package:web_socket_channel/io.dart';

WebSocket.connect("ws://a.b.c.d").then((ws) {

// create the stream channel
var channel = IOWebSocketChannel(ws);

channel.sink.add("hello");
})

包裹 web_socket_channel必须添加到 pubspec.yaml依赖关系。

关于flutter - IOWebSocketChannel 检测连接何时打开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59011160/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com