dart 如何从控制器检测WebSocket连接的打开

h9a6wy2h  于 2023-06-19  发布在  其他
关注(0)|答案(3)|浏览(154)

我有一个控制器(MyController),它在初始化时从WebSocket连接(wsService)请求数据。
检测并等待WebSocket连接打开,然后从控制器发出请求的最佳方法是什么?
现在我使用以下解决方案:
my_controller.dart:

MyController(wsService ws){
  // when refresh() in wsService is called, 
  // the call is redirected to MyController's load()
  ws.refresh = load; 
}

load(){
  ws.send(request);
}

ws_service.dart:

onConnect(){ //this is called when websocket connection is opened
  refresh(); //this calls MyController's load()
}
mkshixfv

mkshixfv1#

我仍然认为你应该做这样的事情,而不是让Angular轮询状态。

MyController(wsService ws){
  if(ws.readyState == WebSocket.OPEN) {
    load();
  } else {
    ws.onOpen.first.then((_) => load());
  }
}

load(){
  ws.send(request);
}
lb3vh1jj

lb3vh1jj2#

这个解决方案仍然使用轮询,但是使用这个解决方案,WebSocket连接的处理被保存在一个地方(wsService),并且在函数调用中没有重复。

MyController(wsService ws){
  new Timer.periodic(new Duration(milliseconds: 100), (t){
    if(ws.webSocket.readyState == WebSocket.OPEN) {
      t.cancel();
      load();
    }
  });
}

load(){
  ws.send(request);
}
sqxo8psd

sqxo8psd3#

使用这个软件包https://pub.dev/packages/websocket_universal,你可以像这样等待连接:

await textSocketHandler.connect();

完整示例:

// ignore_for_file: avoid_print
import 'package:websocket_universal/websocket_universal.dart';

/// Example works with Postman Echo server
void main() async {
  /// 1. Create webSocket handler:
  final textSocketHandler = IWebSocketHandler<String, String>.createClient(
    'wss://ws.postman-echo.com/raw', // Postman echo ws server
    SocketSimpleTextProcessor(),
  );

  /// 2. Listen to webSocket messages:
  textSocketHandler.incomingMessagesStream.listen((inMsg) {
    print('> webSocket  got text message from server: "$inMsg" '
        '[ping: ${textSocketHandler.pingDelayMs}]');
  });
  textSocketHandler.outgoingMessagesStream.listen((inMsg) {
    print('> webSocket sent text message to   server: "$inMsg" '
        '[ping: ${textSocketHandler.pingDelayMs}]');
  });

  /// 3. Connect & send message:
  await textSocketHandler.connect();
  textSocketHandler.sendMessage('Hello server!');
  await Future<void>.delayed(const Duration(seconds: 4));

  // 4. Disconnect & close connection:
  await textSocketHandler.disconnect('manual disconnect');
  textSocketHandler.close();
}

相关问题