EsotericSoftware/kryonet — pull request #52 by codetaylor (2013-12-13 07:11:51+00:00)
Title: Hooking into and providing custom behavior for the host discovery process

I've added a pair of interfaces, ClientDiscoveryHandler and ServerDiscoveryHandler, that can be used to hook into the host discovery interaction and provide custom behavior. The ServerDiscoveryHandler allows a server to return additional information, such as the name of the currently running game or total players connected, in a custom response. The ClientDiscoveryHandler allows a client to process the custom packet returned by the ServerDiscoveryHandler.

Each interface has a nested static implementation that mirrors the existing behavior of Kryonet. These default implementations are assigned to the discoveryHandler member fields in the Server and Client class during construction, and a setter method has been provided to assign a new handler. The empty ByteBuffer that was used in the Server class to send the default empty response has been moved to the default implementation of the ServerDiscoveryHandler.

The ClientDiscoveryHandler interface has three methods:
* __public DatagramPacket onRequestNewDatagramPacket()__ - Implementations of this method should return a new DatagramPacket suitable for reading in the data sent by the ServerDiscoveryHandler.
* __public void onDiscoveredHost(DatagramPacket, Kryo)__ - Called in the Client's onDiscoverHost() and onDiscoverHosts() method when the Client receives a response. The DatagramPacket from the onRequestNewDatagramPacket() method is passed back in as well as the Client's Kryo instance.
* __public void onFinally()__ - Called from the finally clause of the try/catch block within the Client's onDiscoverHost() and onDiscoverHosts() method. This allows the implementation to clean up any used resources like an Input.

The ServerDiscoveryHandler interface has one method:
* __public boolean onDiscoverHost(UdpConnection, InetSocketAddress, Serialization) throws IOException__ - This is the method that is called when the Server receives a DiscoverHost FrameworkMessage. It is responsible for doing something in response to the message, such as the default implementation which sends an empty DatagramPacket across the UdpConnection. It should return a boolean indicating if a response was sent: true if sent, false otherwise. The return value is used only for logging purposes. The UdpConnection, InetSocketAddress and Serialization are passed in, giving the implementation access. The IOException bubbles up from the usage of the UdpConnection#send() method.

All of the existing tests pass with the default handlers and I've extended the DiscoverHostTest to include a test for custom handlers. To the best of my knowledge, no existing behavior has been changed and this shouldn't break any code that uses Kryonet.