Saïd Tahali
Saïd Tahali

Reputation: 199

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

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

Upvotes: 3

Views: 2095

Answers (1)

Justin Fagnani
Justin Fagnani

Reputation: 11171

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

Upvotes: 7

Related Questions