private void PacketReceiverModernAsync(IAsyncResult ar) { if (_baseSock == null || _stream == null || !Connected || Crashed) { return; // -- Terminate cycle } if (_baseSock.Available > 0) { int packetId = 0; byte[] data = new byte[0]; #region No Compression if (!CompressionEnabled) { var packetLength = _stream.ReadVarInt(); if (packetLength == 0) { throw new Exception("Reading Error: Packet Length size is 0"); } packetId = _stream.ReadVarInt(); data = _stream.ReadByteArray(packetLength - 1); } #endregion #region Compression else // (CompressionEnabled) { var packetLength = _stream.ReadVarInt(); if (packetLength == 0) { throw new Exception("Reading Error: Packet Length size is 0"); } var dataLength = _stream.ReadVarInt(); if (dataLength == 0) { if (packetLength >= CompressionThreshold) { throw new Exception("Reading Error: Received uncompressed message of size " + packetLength + " greater than threshold " + CompressionThreshold); } packetId = _stream.ReadVarInt(); data = _stream.ReadByteArray(packetLength - 2); } else // (dataLength > 0) { var dataLengthBytes = MinecraftStream.GetVarIntBytes(dataLength).Length; var tempBuff = _stream.ReadByteArray(packetLength - dataLengthBytes); // -- Compressed using (var outputStream = new MemoryStream()) using (var inputStream = new InflaterInputStream(new MemoryStream(tempBuff))) //using (var reader = new MinecraftDataReader(new MemoryStream(tempBuff), NetworkMode)) { inputStream.CopyTo(outputStream); tempBuff = outputStream.ToArray(); // -- Decompressed packetId = tempBuff[0]; // -- Only 255 packets available. ReadVarInt doesn't work. var packetIdBytes = MinecraftStream.GetVarIntBytes(packetId).Length; data = new byte[tempBuff.Length - packetIdBytes]; Buffer.BlockCopy(tempBuff, packetIdBytes, data, 0, data.Length); } } } #endregion OnDataReceived(packetId, data); } // -- If it will throw an error, then the cause is too slow _stream dispose _stream.EndRead(ar); _stream.BeginRead(new byte[0], 0, 0, PacketReceiverModernAsync, null); }