setCallback method

Future<void> setCallback(
  1. Function onOpen,
  2. Function onError,
  3. Function onClose,
  4. Function onMessage,
)

should set only once

Implementation

Future<void> setCallback(
  Function onOpen,
  Function onError,
  Function onClose,
  Function onMessage,
) async {
  try {
    _ws = await WebSocket.connect(_wsUrl, headers: {
      'origin': 'https://127.0.0.1',
    }); // todo 去掉origin头
  } catch (error) {
    onError(error);
    return;
  }

  var onData = (message) {
    onMessage(message);
  };
  var onDone = () {
    onClose(_ws!.closeCode, _ws!.closeReason);
  };

  _ws!.listen(onData, onError: onError, onDone: onDone);

  if (WebSocket.open == _ws!.readyState) {
    onOpen();
  }
}