public bool ProcessNextSegment(byte[] nextSegment, int offset, int len, out IPacket packet) { packet = null; CurrentPacket = null; if (nextSegment.Length > 0) { PacketBuffer.AddRange(new ByteArraySegment(nextSegment, offset, len)); } if (PacketBuffer.Count == 0) return false; if (CurrentPacket == null) { byte packetId = PacketBuffer[0]; Func<IPacket> createPacket; if (ServerBound) createPacket = PacketReader.ServerboundPackets[packetId]; else createPacket = PacketReader.ClientboundPackets[packetId]; if (createPacket == null) throw new NotSupportedException("Unable to read packet type 0x" + packetId.ToString("X2")); CurrentPacket = createPacket(); } using (ByteListMemoryStream listStream = new ByteListMemoryStream(PacketBuffer, 1)) { using (MinecraftStream ms = new MinecraftStream(listStream)) { try { CurrentPacket.ReadPacket(ms); } catch (EndOfStreamException) { return false; } } PacketBuffer.RemoveRange(0, (int)listStream.Position); } packet = CurrentPacket; CurrentPacket = null; return PacketBuffer.Count > 0; }
public void QueuePacket(IPacket packet) { if (Disconnected || (Connection != null && !Connection.Connected)) return; using (MemoryStream writeStream = new MemoryStream()) { using (MinecraftStream ms = new MinecraftStream(writeStream)) { writeStream.WriteByte(packet.ID); packet.WritePacket(ms); } byte[] buffer = writeStream.ToArray(); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.UserToken = packet; args.Completed += OperationCompleted; args.SetBuffer(buffer, 0, buffer.Length); if (Connection != null) { if (!Connection.SendAsync(args)) OperationCompleted(this, args); } } }