在将消息添加到接收器之前,我无法理解如何检查IOWebSocketChannel
的状态,或者在未发送消息的情况下如何通知错误。
假设Web套接字服务器未监听localhost:8080
,如何检查channel.sink.add
错误或捕获有关失败的套接字发送的异常?
import 'package:web_socket_channel/io.dart';
void main() async {
IOWebSocketChannel channel;
channel = IOWebSocketChannel.connect('ws://localhost:8080/');
channel.stream.listen((data) {}, onError: (err) {
print("err: $err");
}, onDone: () {
print(
"onDone. reason:[${channel.closeReason}], code:[${channel.closeCode}]");
});
print("sending a message");
// how to check that channel's socket is in a connected state?
channel.sink.add("hello");
print("done");
}