Dart How is the websocket pingInterval actually used? Dart How is the websocket pingInterval actually used? dart dart

Dart How is the websocket pingInterval actually used?


I tested it with SDK 1.5.0.dev:

Server code:

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}");          });      });    });  });}

Client code:

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>

For Example, if you close browser window then client-server will close socket with socket.closeReason: , socket.closeCode: 1005 of course you can provide your own reason if it wasn't "sudden death" CloseEvent codes

But if you set pingInterval and press Hang button then server will close socket on timeout but with socket.closeReason: null, socket.closeCode: null. Without pingInterval it will keep waiting.

Probably, Dart team should provide something more 'exhaustive' than null. But you can ping it yourself with Stream timeout

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.