Class PacketHandler


  • public class PacketHandler
    extends java.lang.Object
    • 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 the PacketHandler 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 the DATA_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 be null.
        listener - A listener which is notified when something happens (A packet arrived, the connection failed...). Can be null 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 calling getSender().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.
      • 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. Returns null if automaticPacketProcessing() is true.
        Calling this method will first pass the cached packets to the listeners before it returns them.
        If automaticPacketProcessing() 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 call getCachedPackets() 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 calling sendHandshake(). 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 call sendHandshake().
      • 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 calls PacketListener.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