WebSocketFrame.create constructor

WebSocketFrame.create(
  1. Uint8List data
)

Implementation

WebSocketFrame.create(Uint8List data) {
  WebSocketFrame.buffer.add(data.toList());
  var stream = WebSocketFrame.buffer.toBytes();
  var index = 0;
  var head = stream.first;
  index += 1;
  fin = head & 0x80 != 0;
  opcode = OpCodeExtension.parse(head & opCodeMask);

  valid = isValid(head);

  var second = stream[index];
  index += 1;

  mask = second & maskMask != 0;

  var payloadLen = second & payloadLenMask;

  if (payloadLen < 126) {
    length = payloadLen;
  } else if (payloadLen == 126) {
    length = Uint8List.fromList(stream.getRange(index, index + 2).toList())
        .buffer
        .asByteData()
        .getUint16(0);
    index += 2;
  } else {
    length = Uint8List.fromList(stream.getRange(index, index + 4).toList())
        .buffer
        .asByteData()
        .getUint16(0);
    index += 4;
  }
  if (mask) {
    maskingKey =
        Uint8List.fromList(stream.getRange(index, index + 4).toList());
    index += 4;
  }

  if (valid) {
    payload =
        Uint8List.fromList(stream.getRange(index, index + length).toList());
    if (maskingKey != null) {
      //反掩码
      for (var i = 0; i < payload.length; i++) {
        payload[i] = payload[i] ^ maskingKey![i % 4];
      }
    }
  }
  WebSocketFrame.buffer.clear();
}