close method

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

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();
  }

  if (code != null) {
    RangeError.checkValueInInterval(code, 3000, 4999, 'code');
  }
  if (reason != null && utf8.encode(reason).length > 123) {
    throw ArgumentError.value(reason, 'reason',
        'reason must be <= 123 bytes long when encoded as UTF-8');
  }

  if (!_events.isClosed) {
    unawaited(_events.close());
    if (code != null) {
      reason = reason ?? '';
      _task.cancelWithCloseCode(code, Data.fromList(utf8.encode(reason)));
    } else {
      _task.cancel();
    }
  }
}