Flutter:使用 WebSocket 时收到错误消息“未及时收到 Pong 回复”

问题描述 投票:0回答:1

我正在开发一个 Flutter 应用程序,它使用 WebSockets 连接到 Laravel REVERB 后端。我使用 IOWebSocketChannel.connect 方法建立连接,并使用 sink.add 方法向服务器发送订阅消息。

这是我的 main.dart 文件中的相关代码:

final channel = IOWebSocketChannel.connect(
    'ws://localhost:8080/app/wdkuwjwxw78hbp6sax2c');

@override
void initState() {
  super.initState();
  channel.sink.add(json.encode({
    "event": "pusher:subscribe",
    "data": {"channel": "home"},
  }));
}

一切正常,但延迟后我收到以下错误消息:

{"event":"pusher:error","data":"{\"code\":4201,\"message\":\"Pong reply not received in time\"}"}

这是我的调试控制台 enter image description here

据我了解,此错误消息表示服务器在特定时间范围内未响应 ping 消息。但是,我不确定如何解决这个问题。

有谁知道为什么我可能会收到此错误消息以及如何解决它?任何帮助将不胜感激。

laravel flutter websocket
1个回答
0
投票

答案是我必须监听 websocket 并像这样响应 ping 消息

channel.stream.listen((message) {
  // Print the received message for debugging purposes
  debugPrint(message);

  // Check if the message contains the string 'ping'
  if (message.toString().contains('ping')) {
    // If it does, send a response with the string 'pong'
    channel.sink.add(json.encode(
      {"event": "pusher:pong"},
    ));
    debugPrint('pong');
  }

});
© www.soinside.com 2019 - 2024. All rights reserved.