encodePacket static method

String? encodePacket(
  1. Map packet, {
  2. dynamic supportsBinary,
  3. dynamic utf8encode = false,
  4. required dynamic callback(
    1. dynamic t
    ),
  5. bool fromClient = false,
})

Implementation

static String? encodePacket(Map packet,
    {dynamic supportsBinary,
    utf8encode = false,
    required dynamic Function(dynamic t) callback,
    bool fromClient = false}) {
  if (supportsBinary is Function) {
    callback = supportsBinary as dynamic Function(dynamic);
    supportsBinary = null;
  }

  if (utf8encode is Function) {
    callback = utf8encode as dynamic Function(dynamic);
    utf8encode = null;
  }

  if (packet['data'] != null) {
    if (packet['data'] is Uint8List) {
      return encodeBuffer(packet, supportsBinary, callback,
          fromClient: fromClient);
    } else if (packet['data'] is Map &&
        (packet['data']['buffer'] != null &&
            packet['data']['buffer'] is ByteBuffer)) {
      packet['data'] = (packet['data']['buffer'] as ByteBuffer).asUint8List();
      return encodeBuffer(packet, supportsBinary, callback,
          fromClient: fromClient);
    } else if (packet['data'] is ByteBuffer) {
      packet['data'] = (packet['data'] as ByteBuffer).asUint8List();
      return encodeBuffer(packet, supportsBinary, callback,
          fromClient: fromClient);
    }
  }

  // Sending data as a utf-8 string
  var encoded = '''${packetTypeMap[packet['type']]}''';

  if (packet['data'] != null) {
    encoded += utf8encode == true
        ? WTF8.encode('''${packet['data']}''')
        : '''${packet['data']}''';
  }

  return callback(encoded);
}