HtmlWebSocketChannel constructor

HtmlWebSocketChannel(
  1. WebSocket innerWebSocket
)

Creates a channel wrapping innerWebSocket.

Implementation

HtmlWebSocketChannel(this.innerWebSocket) {
  _readyCompleter = Completer();
  if (innerWebSocket.readyState == WebSocket.OPEN) {
    _readyCompleter.complete();
    _listen();
  } else {
    if (innerWebSocket.readyState == WebSocket.CLOSING ||
        innerWebSocket.readyState == WebSocket.CLOSED) {
      _readyCompleter.completeError(WebSocketChannelException(
          'WebSocket state error: ${innerWebSocket.readyState}'));
    }
    // The socket API guarantees that only a single open event will be
    // emitted.
    innerWebSocket.onOpen.first.then((_) {
      _readyCompleter.complete();
      _listen();
    });
  }

  // The socket API guarantees that only a single error event will be emitted,
  // and that once it is no open or message events will be emitted.
  innerWebSocket.onError.first.then((_) {
    final error = WebSocketChannelException('WebSocket connection failed.');
    _readyCompleter.completeError(error);
    _controller.local.sink.addError(error);
    _controller.local.sink.close();
  });

  innerWebSocket.onMessage.listen((event) {
    var data = event.data;
    if (data is ByteBuffer) data = data.asUint8List();
    _controller.local.sink.add(data);
  });

  // The socket API guarantees that only a single error event will be emitted,
  // and that once it is no other events will be emitted.
  innerWebSocket.onClose.first.then((event) {
    _closeCode = event.code;
    _closeReason = event.reason;
    _controller.local.sink.close();
  });
}