felangel / web_socket_client

A simple WebSocket client for Dart which includes automatic reconnection logic.
https://pub.dev/packages/web_socket_client
MIT License
150 stars 32 forks source link

feat: Add an asynchronous `close()` method #29

Closed Switernal closed 3 months ago

Switernal commented 1 year ago

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?

felangel commented 3 months ago

This is fixed in v0.1.4 🎉