gpt4 book ai didi

websocket - Dart 的 websocket pingInterval 实际是如何使用的?

转载 作者:行者123 更新时间:2023-12-03 03:19:00 28 4
gpt4 key购买 nike

我一直在使用网络套接字进行测试,并想使用 pingInterval 来确定客户端是否已关闭,但我一直无法检测到。我每 4 秒通过 websocket 发送一条消息。我想,当我退出浏览器时,不会产生任何错误情况,而且我一直无法弄清楚如何检测网络套接字是否关闭了连接。我怎样才能检测到?我也是 Dart 和网络应用程序的新手。

最佳答案

我用 SDK 1.5.0.dev 测试了它:

服务器代码:

import 'dart:io';
main() {
HttpServer.bind('127.0.0.1', 4040).then((server) {
server.listen((HttpRequest request) {
WebSocketTransformer.upgrade(request).then((socket) {
socket.listen((msg){
socket.pingInterval = new Duration(seconds : 1);
print('server received message: $msg');
socket.add('server received message: $msg');
});
socket.done.then((e){
print("WebSocket closed with:"
"socket.closeReason: ${socket.closeReason}, "
"socket.closeCode: ${socket.closeCode}");
});
});
});
});
}

客户端代码:

import 'dart:html';
import 'dart:async';
void main() {
querySelector('button').onClick.first.then((e){
for (int i = 0; i > -1; i++){
print("epic code");
}
});
WebSocket ws = new WebSocket('ws://127.0.0.1:4040');
ws.onMessage.listen((MessageEvent e) {
querySelector('#response').appendHtml('<p>${e.data}</p>');
});
Timer t = new Timer.periodic(new Duration(seconds : 1), (t) {
ws.sendString('timer fired');
});
}

html:

<!DOCTYPE html>

<html>
<head>
<meta charset="utf-8">
<title>ClientTest</title>
<link rel="stylesheet" href="clienttest.css">
</head>
<body>
<button type="button">Hang</button>
<p>Response:</p>

<div id="response">
</div>

<script type="application/dart" src="clienttest.dart"></script>
<script src="packages/browser/dart.js"></script>
</body>
</html>

例如,如果您关闭浏览器窗口,那么客户端-服务器将关闭带有 socket.closeReason: , socket.closeCode: 1005 的套接字,当然如果不是,您可以提供您自己的原因“猝死” CloseEvent codes

但是,如果您设置了 pingInterval 并按下了 Hang 按钮,那么服务器将在超时时关闭套接字,但是 socket.closeReason: null, socket.closeCode: null。如果没有 pingInterval,它将一直等待。

Dart 团队可能应该提供比 null 更“详尽”的内容。但是你可以自己用Stream timeout ping它

Stream timeout(Duration timeLimit, {Function void onTimeout(EventSink sink)})

Creates a new stream with the same events as this stream.

Whenever more than timeLimit passes between two events from this stream, the onTimeout function is called.

The countdown doesn't start until the returned stream is listened to. The countdown is reset every time an event is forwarded from this stream, or when the stream is paused and resumed.

The onTimeout function is called with one argument: an EventSink that allows putting events into the returned stream. This EventSink is only valid during the call to onTimeout.

If onTimeout is omitted, a timeout will just put a TimeoutException into the error channel of the returned stream.

The returned stream is not a broadcast stream, even if this stream is.

关于websocket - Dart 的 websocket pingInterval 实际是如何使用的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23975652/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com