how does WebSocketChannel warns that it disconnected?

Issue

I am using WebSocketChannel as a socket server:

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

How can I know when the webSocket above gets disconnected?

Solution

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}]');
  });
});

Answered By – attdona

Answer Checked By – David Marino (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *