Merge pull request #20 from ipbeegle/add-bufferedpacket

Add BufferedPacket
This commit is contained in:
Steven Smith 2020-05-21 11:30:08 -07:00 committed by GitHub
commit dbefdf50b4
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 58 additions and 6 deletions

View file

@ -0,0 +1,36 @@
package com.github.steveice10.packetlib.packet;
import com.github.steveice10.packetlib.io.NetInput;
import com.github.steveice10.packetlib.io.NetOutput;
import java.io.EOFException;
import java.io.IOException;
public class BufferedPacket implements Packet {
private Class<? extends Packet> packetClass;
private byte[] buf;
public BufferedPacket(Class<? extends Packet> packetClass, byte[] buf) {
this.packetClass = packetClass;
this.buf = buf;
}
public Class<? extends Packet> getPacketClass() {
return packetClass;
}
@Override
public void read(NetInput in) throws IOException {
throw new EOFException("BufferedPacket can not be read");
}
@Override
public void write(NetOutput out) throws IOException {
out.writeBytes(buf);
}
@Override
public boolean isPriority() {
return true;
}
}

View file

@ -132,15 +132,31 @@ public abstract class PacketProtocol {
/**
* Gets the registered id of an outgoing packet class.
*
* @param packet Class of the packet to get the id for.
* @param packetClass Class of the packet to get the id for.
* @return The packet's registered id.
* @throws IllegalArgumentException If the packet is not registered.
*/
public final int getOutgoingId(Class<? extends Packet> packet) {
if(!this.outgoing.containsKey(packet) || this.outgoing.get(packet) == null) {
throw new IllegalArgumentException("Unregistered outgoing packet class: " + packet.getName());
public final int getOutgoingId(Class<? extends Packet> packetClass) {
Integer packetId = this.outgoing.get(packetClass);
if(packetId == null) {
throw new IllegalArgumentException("Unregistered outgoing packet class: " + packetClass.getName());
}
return this.outgoing.get(packet);
return packetId;
}
/**
* Gets the registered id of an outgoing {@link Packet} instance.
*
* @param packet Instance of {@link Packet} to get the id for.
* @return The packet's registered id.
* @throws IllegalArgumentException If the packet is not registered.
*/
public final int getOutgoingId(Packet packet) {
if(packet instanceof BufferedPacket) {
return getOutgoingId(((BufferedPacket)packet).getPacketClass());
}
return getOutgoingId(packet.getClass());
}
}

View file

@ -23,7 +23,7 @@ public class TcpPacketCodec extends ByteToMessageCodec<Packet> {
@Override
public void encode(ChannelHandlerContext ctx, Packet packet, ByteBuf buf) throws Exception {
NetOutput out = new ByteBufNetOutput(buf);
this.session.getPacketProtocol().getPacketHeader().writePacketId(out, this.session.getPacketProtocol().getOutgoingId(packet.getClass()));
this.session.getPacketProtocol().getPacketHeader().writePacketId(out, this.session.getPacketProtocol().getOutgoingId(packet));
packet.write(out);
}