close method

  1. @override
Future<void> close([
  1. int? code,
  2. String? reason
])
override

Closes the WebSocket connection and the events Stream.

Sends a Close frame to the peer. If the optional code and reason arguments are given, they will be included in the Close frame. If no code is set then the peer will see a 1005 status code. If no reason is set then the peer will not receive a reason string.

Throws an ArgumentError if code is not 1000 or in the range 3000-4999.

Throws an ArgumentError if reason is longer than 123 bytes when encoded as UTF-8

Throws WebSocketConnectionClosed if the connection is already closed (including by the peer).

Implementation

@override
Future<void> close([int? code, String? reason]) async {
  if (_events.isClosed) {
    throw WebSocketConnectionClosed();
  }

  checkCloseCode(code);
  checkCloseReason(reason);

  unawaited(_events.close());
  try {
    await _webSocket.close(code, reason);
  } on io.WebSocketException catch (e) {
    throw WebSocketException(e.message);
  }
}