web_socket_client icon indicating copy to clipboard operation
web_socket_client copied to clipboard

feat: Add an asynchronous `close()` method

Open Switernal opened this issue 2 years ago • 0 comments

Description

I want to close the connection immediately upon receiving a specific notification from the server within the socket.messages.listen() method, like this:

socket.messages.listen((message) {
  print('onMessage');
  if (message is String && message == 'shut down connection') {
    socket.close();
  }
});

However, if the server sends another message immediately while the connection is still in the process of closing, it will cause a problem: a new message is received before the connection closed completely, causing a duplicate call to the close() method. It will throw an exception:

Unhandled exception:
Bad state: Cannot add new events after calling close
#0      _BroadcastStreamController.add (dart:async/broadcast_stream_controller.dart:243:24)
#1      ConnectionController.add (package:web_socket_client/src/connection.dart:50:17)
#2      WebSocket.close (package:web_socket_client/src/web_socket.dart:156:27)
<asynchronous suspension>

Requirements

Currently, the close() method in web_socket.dart is synchronous. Could you add an asynchronous version to avoid this situation?

Switernal avatar Aug 16 '23 11:08 Switernal