public static async Task <Packet> ReadFromStreamAsync(MinecraftStream stream) { int length = await stream.ReadVarIntAsync(); byte[] receivedData = new byte[length]; await stream.ReadAsync(receivedData, 0, length); int packetId = 0; byte[] packetData = new byte[0]; using (var packetStream = new MinecraftStream(receivedData)) { try { packetId = await packetStream.ReadVarIntAsync(); int arlen = 0; if (length - packetId.GetVarintLength() > -1) { arlen = length - packetId.GetVarintLength(); } packetData = new byte[arlen]; await packetStream.ReadAsync(packetData, 0, packetData.Length); } catch { throw; } } return(new EmptyPacket(packetId, packetData)); }
private async Task <(int id, byte[] data)> GetNextPacketAsync() { int length = await this.minecraftStream.ReadVarIntAsync(); byte[] receivedData = new byte[length]; await this.minecraftStream.ReadAsync(receivedData, 0, length); int packetId = 0; byte[] packetData = Array.Empty <byte>(); using (var packetStream = new MinecraftStream(receivedData)) { try { packetId = await packetStream.ReadVarIntAsync(); int arlen = 0; if (length - packetId.GetVarIntLength() > -1) { arlen = length - packetId.GetVarIntLength(); } packetData = new byte[arlen]; await packetStream.ReadAsync(packetData, 0, packetData.Length); } catch { throw; } } return(packetId, packetData); }
public static async Task <T> DeserializeAsync <T>(byte[] data) where T : Packet { await using var stream = new MinecraftStream(data); var packet = (T)Activator.CreateInstance(typeof(T));//TODO make sure all packets have default constructors if (packet == null) { throw new NullReferenceException(nameof(packet)); } //Program.PacketLogger.LogDebug($"Deserializing {packet}"); var valueDict = packet.GetAllMemberNames().OrderBy(x => x.Key.Order); var members = packet.GetType().GetMembers(PacketExtensions.Flags); int readableBytes = 0; foreach (var(key, value) in valueDict) { var member = members.FirstOrDefault(x => x.Name.EqualsIgnoreCase(value)); if (member is FieldInfo field) { var dataType = key.Type; if (dataType == DataType.Auto) { dataType = field.FieldType.ToDataType(); } var val = await stream.ReadAsync(field.FieldType, dataType, key); //Program.PacketLogger.LogDebug($"Setting val {val}"); field.SetValue(packet, val); } else if (member is PropertyInfo property) { var dataType = key.Type; if (dataType == DataType.Auto) { dataType = property.PropertyType.ToDataType(); } var val = await stream.ReadAsync(property.PropertyType, dataType, key, readableBytes); //Program.PacketLogger.LogDebug($"Setting val {val}"); if (property.PropertyType.IsEnum && property.PropertyType == typeof(BlockFace)) { val = (BlockFace)val; } property.SetValue(packet, val); } readableBytes = data.Length - (int)stream.Position; } return(packet); }