public IncomingPacket Parse(SocketManager manager, BufferSegment data, TransportEventTypes transportEvent = TransportEventTypes.Unknown) { using (var stream = new System.IO.MemoryStream(data.Data, data.Offset, data.Count)) { var buff = BufferPool.Get(MsgPackReader.DEFAULT_BUFFER_SIZE, true); try { var context = new SerializationContext { Options = SerializationOptions.SuppressTypeInformation/*, * ExtensionTypeHandler = CustomMessagePackExtensionTypeHandler.Instance*/ }; IJsonReader reader = new MsgPackReader(stream, context, Endianness.BigEndian, buff); reader.ReadObjectBegin(); int type = -1, id = -1; string nsp = null; bool hasData = false, readData = false; IncomingPacket packet = IncomingPacket.Empty; READ: while (reader.Token != JsonToken.EndOfObject) { string key = reader.ReadMember(); switch (key) { case "type": type = reader.ReadByte(); break; case "nsp": nsp = reader.ReadString(); break; case "id": id = reader.ReadInt32(); break; case "data": if (!hasData) { hasData = true; SkipData(reader, (SocketIOEventTypes)type); } else { readData = true; packet = new IncomingPacket(transportEvent != TransportEventTypes.Unknown ? transportEvent : TransportEventTypes.Message, (SocketIOEventTypes)type, nsp, id); (string eventName, object[] args) = ReadData(manager, packet, reader); packet.EventName = eventName; if (args != null) { if (args.Length == 1) { packet.DecodedArg = args[0]; } else { packet.DecodedArgs = args; } } } break; } } // type, nsp, id and data can come in any order. To read data strongly typed we need to know all the additional fields before processing the data field. // In order to do it, when we first encounter the data field we skip it than we do a reset and an additional turn but reading the data too now. if (hasData && !readData) { reader.Reset(); stream.Position = 0; reader.ReadObjectBegin(); goto READ; } reader.ReadObjectEnd(); return(packet.Equals(IncomingPacket.Empty) ? new IncomingPacket(transportEvent != TransportEventTypes.Unknown ? transportEvent : TransportEventTypes.Message, (SocketIOEventTypes)type, nsp, id) : packet); } finally { BufferPool.Release(buff); } } }