Skip to content

Commit

Permalink
fix: implement pings for websocket on browser
Browse files Browse the repository at this point in the history
  • Loading branch information
Kuruyia committed Dec 22, 2023
1 parent 056a310 commit 642afaf
Show file tree
Hide file tree
Showing 5 changed files with 133 additions and 65 deletions.
2 changes: 1 addition & 1 deletion lib/src/protocols/websocket.dart
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ class WebSocketProtocol extends KuzzleWebSocket {
bool autoReconnect = true,
Duration reconnectionDelay = const Duration(seconds: 1),
int reconnectionAttempts = 10,
Duration? pingInterval,
Duration pingInterval = const Duration(seconds: 2),
}) : super(
uri,
autoReconnect: autoReconnect,
Expand Down
14 changes: 12 additions & 2 deletions lib/src/protocols/websocket_browser.dart
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,16 @@ class KuzzleWebSocket extends KuzzleProtocol {
bool autoReconnect = true,
Duration reconnectionDelay = const Duration(seconds: 1),
int reconnectionAttempts = 10,
this.pingInterval,
required this.pingInterval,
}) : super(uri,
autoReconnect: autoReconnect,
reconnectionDelay: reconnectionDelay,
reconnectionAttempts: reconnectionAttempts);

WebSocket? _webSocket;
StreamSubscription? _subscription;
Duration? pingInterval;
Duration pingInterval;
Timer? pingTimer;

@override
Future<void> protocolConnect() async {
Expand All @@ -42,6 +43,15 @@ class KuzzleWebSocket extends KuzzleProtocol {

_subscription = _webSocket!.onMessage.listen(_handlePayload);

pingTimer?.cancel();
pingTimer = Timer.periodic(pingInterval, (timer) {
if (_webSocket != null && _webSocket!.readyState == WebSocket.OPEN) {
_webSocket!.sendString('{"p":1}');
} else {
timer.cancel();
}
});

final onErrorSubscription =
_webSocket!.onError.listen(_connected.completeError);

Expand Down
4 changes: 2 additions & 2 deletions lib/src/protocols/websocket_io.dart
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,15 @@ class KuzzleWebSocket extends KuzzleProtocol {
bool autoReconnect = true,
Duration reconnectionDelay = const Duration(seconds: 1),
int reconnectionAttempts = 10,
this.pingInterval,
required this.pingInterval,
}) : super(uri,
autoReconnect: autoReconnect,
reconnectionDelay: reconnectionDelay,
reconnectionAttempts: reconnectionAttempts);

WebSocket? _webSocket;
StreamSubscription? _subscription;
Duration? pingInterval;
Duration pingInterval;

@override
Future<void> protocolConnect() async {
Expand Down
Loading

0 comments on commit 642afaf

Please sign in to comment.