3

I am using WebSocketChannel as a socket server:

var handler = webSocketHandler((WebSocketChannel webSocket) async {
}

How can I know when the webSocket above gets disconnected?

Jonathan
  • 4,724
  • 7
  • 45
  • 65

2 Answers2

4

You have to listen on the channel stream and intercept the close event with the onDone callback.

closeCode and closeReason properties give you details about the close.

webSocketHandler((channel) {
  channel.stream.listen((data) {
    channel.sink.add('Echo: $data');
  },
  onDone: () {
    print('socket closed: reason=[${channel.closeReason}], code:[${channel.closeCode}]');
  });
});
attdona
  • 17,196
  • 7
  • 49
  • 60
1

Even thought there is a correct answer to this thread, I ended up using another package for handling socket connections: https://pub.dartlang.org/packages/socket_io

Jonathan
  • 4,724
  • 7
  • 45
  • 65