Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i know if i'm disconnected from a Dart websocket server

Tags:

websocket

dart

I created a WebSocket server, and it works just fine, however, i don't know how to detect if a client is disconnected, can anyone help me ?

here is my code:

import 'dart:io';
const port=8080;
List users=new List();

void main() {

  HttpServer.bind('127.0.0.1', port)
    .then((HttpServer server)=>
      server.listen((HttpRequest request) =>

          WebSocketTransformer.upgrade(request).then((WebSocket websocket) {
            //what can i do here to detect if my websocket is closed
            users.add(websocket);
            websocket.add("clients Number is ${users.length}");
          })
      )
   );
}
like image 730
Saïd Tahali Avatar asked Sep 05 '25 19:09

Saïd Tahali


1 Answers

Since a WebSocket is a Stream it will close when the socket is disconnected. This is a nice property of many of the dart:io classes implementing Stream - you can interact with them al lthe same way, once you know how to use Streams.

You can detect when a Stream closes in several ways:

  1. Add an onDone handler to your listen() call:

    websocket.listen(handler, onDone: doneHandler);
    
  2. Add an on-done handler to the StreamSubscription returned from listen():

    var sub = websocket.listen(handler);
    sub.onDone(doneHandler);
    
  3. Turn the StreamSubscription into a Future via asFuture() and wait for it to complete:

    var sub = websocket.listen(handler);
    sub.asFuture().then((_) => doneHandler);
    
like image 86
Justin Fagnani Avatar answered Sep 08 '25 12:09

Justin Fagnani