我正在开发一个 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\"}"}
据我了解,此错误消息表示服务器在特定时间范围内未响应 ping 消息。但是,我不确定如何解决这个问题。
有谁知道为什么我可能会收到此错误消息以及如何解决它?任何帮助将不胜感激。
答案是我必须监听 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');
}
});