dart IOWebSocketChannel检测连接何时打开

6qftjkof  于 12个月前  发布在  其他
关注(0)|答案(2)|浏览(80)

我是个新手。我正在尝试使用WebSocketChannel连接到WebSocket服务器。
是否有方法检测与服务器的连接何时完成?
我想做的是在与服务器连接完成的那一刻发送一些消息。
在JavaScript实现中,这是这样做的:

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

dart/flutter是否有替代方案?是否可以与WebSocketChannel一起使用

wd2eg0qa

wd2eg0qa1#

WebSocket类的静态方法connect返回一个Future,该Future在建立连接时解析为Web Socket。
如果你想在连接建立时发送一条消息,应该可以这样做:

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依赖项中。

vuktfyat

vuktfyat2#

WebSocketChannel 2.4.0的最新版本中,有ready Future。

import 'package:web_socket_channel/io.dart';

final channel = IOWebSocketChannel.connect('ws://localhost:3000',
      connectTimeout: Duration(seconds: 20),
      pingInterval: Duration(seconds: 15));

channel.stream.listen((event) {
  print('got message');
});

await channel.ready; // ready is a future

print('WS connected');

channel.sink.add('hi'); // write data to websocket

相关问题