Package com.germancoding.packetapi
Class PacketHandler
- java.lang.Object
-
- com.germancoding.packetapi.PacketHandler
-
public class PacketHandler extends java.lang.Object
-
-
Field Summary
Fields Modifier and Type Field Description static int
DATA_TIMEOUT
Timeout (in MS) after which KeepAlive packets should be send.static int
HANDSHAKE_ID_REQUEST
Handshake ID used in the sendHandshake() method.static int
HANDSHAKE_ID_RESPONSE
Handshake ID used when replying to a handshake packet.protected java.io.InputStream
in
java.util.logging.Logger
logger
protected java.io.OutputStream
out
static int
PROTOCOL_VERSION
Applications can change this value if they want.
-
Constructor Summary
Constructors Constructor Description PacketHandler(java.io.InputStream in, java.io.OutputStream out, java.lang.String connectionName, PacketListener listener)
Creates a new PacketHandler instance.
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description boolean
automaticPacketProcessing()
boolean
autoSendKeepAlive()
void
close()
Closes the connection, the I/O streams and notfies the other side that we are closing this connection.java.util.List<Packet>
getCachedPackets()
Returns all packets that have not been processed yet.java.lang.String
getConnectionName()
DefaultPacketListener
getDefaultPacketListener()
long
getLastPacketReceived()
long
getLastPacketSend()
PacketListener
getListener()
Packet
getNewPacketInstance(short id)
DataReader
getReader()
int
getRemoteProtocolVersion()
DataSender
getSender()
boolean
isClosed()
boolean
isHandshakeSend()
boolean
isInstantFlush()
boolean
isVersionApproved()
void
notifyOnDefaultPackets(boolean notify)
Sets whether this library callsPacketListener.onPacketReceived()
when default packets are received.void
onConnectionClosed(java.lang.String message, boolean expected)
Notifies this instance that the connection is closed (or will be closed now) for an external reason.void
onConnectionFail(java.lang.Exception e)
Notifies this instance that the connection has failed.void
onPacketReceived(Packet packet)
Called when a new packet was received.void
onUnknownPacketReceived(short id)
void
registerPacket(java.lang.Class<? extends Packet> packetClass)
Registers a new packet.void
sendHandshake()
Sends a handshake to exchange version numbers.void
sendHandshake(int id)
Sends a handshake using the given id as the handshake id.void
sendPacket(Packet p)
Sends the given packet by adding it to the sending queue.void
setAutomaticPacketProcessing(boolean on)
void
setAutoSendKeepAlive(boolean autoSendKeepAlive)
void
setConnectionName(java.lang.String connectionName)
protected void
setDefaultPacketListener(DefaultPacketListener defaultPacketListener)
void
setHandshakeSend(boolean handshakeSend)
void
setInstantFlush(boolean instantFlush)
void
setLastPacketReceived(long lastPacketReceived)
void
setLastPacketSend(long lastPacketSend)
void
setListener(PacketListener listener)
void
setReader(DataReader s)
void
setRemoteProtocolVersion(int remoteProtocolVersion)
void
setSender(DataSender s)
void
setVersionApproved(boolean versionApproved)
boolean
shouldSendKeepAlive()
void
shutdown()
Shuts down this PacketHandler instance silently without touching the underlying streams or sockets.
-
-
-
Field Detail
-
PROTOCOL_VERSION
public static int PROTOCOL_VERSION
Applications can change this value if they want. Default is 1
-
HANDSHAKE_ID_REQUEST
public static final int HANDSHAKE_ID_REQUEST
Handshake ID used in the sendHandshake() method. The other side will respond to that packet. Default is 0- See Also:
- Constant Field Values
-
HANDSHAKE_ID_RESPONSE
public static final int HANDSHAKE_ID_RESPONSE
Handshake ID used when replying to a handshake packet. The other side will not respond to that packet. Default is 1- See Also:
- Constant Field Values
-
DATA_TIMEOUT
public static int DATA_TIMEOUT
Timeout (in MS) after which KeepAlive packets should be send. Default is 20.000 ms
-
logger
public java.util.logging.Logger logger
-
in
protected java.io.InputStream in
-
out
protected java.io.OutputStream out
-
-
Constructor Detail
-
PacketHandler
public PacketHandler(java.io.InputStream in, java.io.OutputStream out, java.lang.String connectionName, PacketListener listener)
Creates a new PacketHandler instance. The instance will use the given I/O streams to send and receive data.
Note about timeouts: When the I/O stream reads from a UDP socket (or any other protocol that deals with timeouts), beware of the socket timeout value! If thePacketHandler
runs into a timeout, the connection will be marked as failed and will be terminated. To avoid this, set the timeout to zero or set it to something higher then theDATA_TIMEOUT
and use the keep-alive function.- Parameters:
in
- The InputStream to read data from.out
- The OutputStream to send data to.connectionName
- Optional: Give the connection a name to identify it. Can benull
.listener
- A listener which is notified when something happens (A packet arrived, the connection failed...). Can benull
if the application does not want to listen to incoming data.
-
-
Method Detail
-
registerPacket
public void registerPacket(java.lang.Class<? extends Packet> packetClass) throws java.lang.Exception
Registers a new packet. After registering the packet type can be send and received.- Parameters:
packetClass
- The class of the new packet.- Throws:
java.lang.Exception
- If reflection fails, like when there is no nullary constructor.
-
getNewPacketInstance
public Packet getNewPacketInstance(short id)
-
sendPacket
public void sendPacket(Packet p)
Sends the given packet by adding it to the sending queue. Sendings packets that are not registered is possible, but is not recommended. Calling this method has the same effect as callinggetSender().sendPacket(p)
- Parameters:
p
- The packet to send.
-
onConnectionFail
public void onConnectionFail(java.lang.Exception e)
Notifies this instance that the connection has failed. This method notifies the listeners and closes the connection- Parameters:
e
- An exception describing why the connection has failed.
-
onConnectionClosed
public void onConnectionClosed(java.lang.String message, boolean expected)
Notifies this instance that the connection is closed (or will be closed now) for an external reason.- Parameters:
message
- Message why the connection was closed.expected
- Whether this was expected (like there was a close packet) or not (like when the underlying socket is closed without notification)
-
close
public void close()
Closes the connection, the I/O streams and notfies the other side that we are closing this connection.
-
getConnectionName
public java.lang.String getConnectionName()
- Returns:
- The name of this connection.
-
setConnectionName
public void setConnectionName(java.lang.String connectionName)
-
getReader
public DataReader getReader()
- Returns:
- The reader which is reading data from the InputStream.
-
getSender
public DataSender getSender()
- Returns:
- The sender which is sending data to the OutputStream.
-
getListener
public PacketListener getListener()
- Returns:
- The application/user listener.
-
setListener
public void setListener(PacketListener listener)
-
getDefaultPacketListener
public DefaultPacketListener getDefaultPacketListener()
- Returns:
- The listener used by the PacketAPI for default packets.
-
setDefaultPacketListener
protected void setDefaultPacketListener(DefaultPacketListener defaultPacketListener)
-
onPacketReceived
public void onPacketReceived(Packet packet)
Called when a new packet was received.- Parameters:
packet
- The packet just received.
-
onUnknownPacketReceived
public void onUnknownPacketReceived(short id)
-
isClosed
public boolean isClosed()
- Returns:
- Whether the connection was closed (using the close() function of this class) or not.
-
sendHandshake
public void sendHandshake()
Sends a handshake to exchange version numbers. You have to call this method if you want to use state attributes like isVersionApproved().
-
sendHandshake
public void sendHandshake(int id)
Sends a handshake using the given id as the handshake id.- Parameters:
id
- The handshake id.
-
getCachedPackets
public java.util.List<Packet> getCachedPackets()
Returns all packets that have not been processed yet. Returnsnull
ifautomaticPacketProcessing()
is true.
Calling this method will first pass the cached packets to the listeners before it returns them.
IfautomaticPacketProcessing()
is false, it is recommended to call this method frequently otherwise no packets will get processed.- Returns:
- All packets in the queue or an empty list. Only
null
if packets are automatically processed and the queue is empty. - See Also:
automaticPacketProcessing()
-
automaticPacketProcessing
public boolean automaticPacketProcessing()
- Returns:
- Whether automatic packet processing is on. If true, packets will be passed directly to the listener after receiving. This is done on an async thread (called DataReader).
In some cases you may want to handle to the incoming packets on your (main) thread. To achieve this, set automatic packet processing to false and callgetCachedPackets()
frequently to get your packets processed on your thread.
Default is true.
-
setAutomaticPacketProcessing
public void setAutomaticPacketProcessing(boolean on)
-
isVersionApproved
public boolean isVersionApproved()
- Returns:
- Whether the protocol version is approved. The protocol version is approved when both peers have the same protocol version.
To request a version check, simply send a handshake packet by callingsendHandshake()
. After receiving the response from the other side and comparing the version numbers, the version will be approved.
-
setVersionApproved
public void setVersionApproved(boolean versionApproved)
-
isHandshakeSend
public boolean isHandshakeSend()
- Returns:
- Whether this side has send a handshake packet.
Note: Handshake packets are not send automatically, you have to callsendHandshake()
.
-
setHandshakeSend
public void setHandshakeSend(boolean handshakeSend)
-
getRemoteProtocolVersion
public int getRemoteProtocolVersion()
- Returns:
- The protocol version of the other peer or -1 if the version used by the other peer is unknown (e.g no handshake was send)
-
setRemoteProtocolVersion
public void setRemoteProtocolVersion(int remoteProtocolVersion)
-
getLastPacketReceived
public long getLastPacketReceived()
- Returns:
- The timestamp when the last packet was (successfull) received. 0 if no packet was received yet.
-
setLastPacketReceived
public void setLastPacketReceived(long lastPacketReceived)
-
getLastPacketSend
public long getLastPacketSend()
- Returns:
- The timestamp when the last packet was send. 0 if no packet was send yet.
-
setLastPacketSend
public void setLastPacketSend(long lastPacketSend)
-
autoSendKeepAlive
public boolean autoSendKeepAlive()
- Returns:
- Whether the library automatically sends packets to keep the connection alive. Default is false.
-
setAutoSendKeepAlive
public void setAutoSendKeepAlive(boolean autoSendKeepAlive)
-
shouldSendKeepAlive
public boolean shouldSendKeepAlive()
- Returns:
- If no data is send or received by the application for some time, this value returns true.
- See Also:
DATA_TIMEOUT
-
notifyOnDefaultPackets
public void notifyOnDefaultPackets(boolean notify)
Sets whether this library callsPacketListener.onPacketReceived()
when default packets are received.- Parameters:
notify
- Whether to notify your PacketListener when we receive default packets. Normally, only the DefaultPacketListener gets notified.
-
isInstantFlush
public boolean isInstantFlush()
- Returns:
- If the OutputStream is immediatly flushed after a packet has been send. This is usually not needed, but COULD improve ping times. Default is false
-
setInstantFlush
public void setInstantFlush(boolean instantFlush)
-
shutdown
public void shutdown()
Shuts down this PacketHandler instance silently without touching the underlying streams or sockets.
-
setSender
public void setSender(DataSender s) throws java.lang.InterruptedException
- Throws:
java.lang.InterruptedException
-
setReader
public void setReader(DataReader s) throws java.lang.InterruptedException
- Throws:
java.lang.InterruptedException
-
-