Menu

Getting started

Alex Gotev

Getting started

Prerequisites

Download the latest autodiscovery library JARs (autodiscovery.zip) and add autodiscovery.jar to your project dependencies.



Hello world!

The event listener

AutoDiscovery library is event-based, so first of all we have to write the event listener, that is responsible of handling the events sent by the library to suit your specific needs. In this tutorial we're going to only log each event to keep things as simple as possible.

:::java

package net.gotev.autodiscovery.example;

import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.gotev.autodiscovery.AutoDiscovery;
import net.gotev.autodiscovery.AutoDiscoveryListener;
import net.gotev.autodiscovery.AutoDiscoveryPeer;

/**
 * Implementation of the {@link AutoDiscoveryListener} interface to listen for
 * auto discovery events.
 * @author Alex Gotev
 */
public class MyCustomListener implements AutoDiscoveryListener {

    /**
     * Instance of the logger used by this listener.
     */
    private static final Logger LOGGER =
            Logger.getLogger(MyCustomListener.class.getName());

    /**
     * Method called when a new peer has been discovered.
     * @param newPeer new peer data
     */
    @Override
    public final void newPeer(final AutoDiscoveryPeer newPeer) {
        LOGGER.info("New peer found! IP: " + newPeer.getIpAddress()
                    + ", UDP Port: " + newPeer.getUdpPort() + "\n"
                    + getParametersString(newPeer));
    }

    /**
     * Method called when a previously discovered peer has gone offline.
     * @param removedPeer removed peer data
     */
    @Override
    public final void removedPeer(final AutoDiscoveryPeer removedPeer) {
        LOGGER.info("A peer has gone! IP: " + removedPeer.getIpAddress()
                    + ", UDP Port: " + removedPeer.getUdpPort() + "\n"
                    + getParametersString(removedPeer));
    }

    /**
     * Method called when the library dispatches a debug message.
     * By default, debugging messages are disabled.
     * To enable them, see the method {@code setDebugEnabled} of
     * {@link AutoDiscovery} class.
     * @param message debug message
     */
    @Override
    public final void debug(final String message) {
        LOGGER.info(message);
    }

    /**
     * Method called if the auto discovery thread gets stopped because an
     * error occurred.
     * @param instance instance in which the exception occurred
     * @param exception exception (with full stack trace) that caused the error
     */
    @Override
    public final void errorOccurred(final AutoDiscovery instance,
                                    final Throwable exception) {
        LOGGER.log(Level.SEVERE, "Ouch! Houston we have a problem!", exception);
    }

    /**
     * Gets the string representation of peer's parameters.
     * @param peer peer
     * @return string
     */
    private String getParametersString(final AutoDiscoveryPeer peer) {
        final Set<String> paramKeys = peer.getParameterKeys();

        final StringBuilder output = new StringBuilder();

        output.append("Parameters: ")
              .append(paramKeys.size())
              .append("\n");

        if (!paramKeys.isEmpty()) {
            for (String key : paramKeys) {
                output.append(key)
                      .append(" = ")
                      .append(peer.getParameter(key))
                      .append("\n");
            }
        }

        return output.toString();
    }
}


The main

After that we've implemented the event listener, we're ready to see how to instantiate and configure the AutoDiscovery library and to run our first application!

:::java

package net.gotev.autodiscovery.example;

import java.io.IOException;
import java.util.logging.Logger;
import net.gotev.autodiscovery.AutoDiscovery;

/**
 * Example of how to use auto discovery in your application.
 *
 * @author Alex Gotev
 */
public class AutoDiscoveryExample {

    /**
     * Port on which to run the auto discovery.
     */
    private static final int UDP_PORT = 7447;

    /**
     * How many seconds to wait for other peers before terminating the program.
     */
    private static final int SECONDS = 30;

    /**
     * Constant that indicates if the debugging messages are enabled.
     */
    private static final boolean DEBUG_ENABLED = true;

    /**
     * Instance of the logger that will be used.
     */
    private static final Logger LOGGER =
            Logger.getLogger(AutoDiscoveryExample.class.getName());

    public static void main(String[] args) throws IOException, InterruptedException {

        //Create a new instance of the AutoDiscovery class on a custom UDP port
        final AutoDiscovery autoDiscovery = new AutoDiscovery(UDP_PORT);

        //Call this method only if you want to enable debug messages
        //because they are disabled by default
        autoDiscovery.setDebugEnabled(DEBUG_ENABLED);

        //Sets how often (in seconds) to send a "Hello" broadcast message.
        //By default, a "Hello" broadcast message gets sent each 30 seconds
        autoDiscovery.setSendBroadcastEvery(5);

        //Register the auto discovery events listener
        autoDiscovery.addListener(new MyCustomListener());

        //Add your own custom parameters, that you want other peers to see
        //when they discover you
        autoDiscovery.addParameter("library", "AutoDiscovery");
        autoDiscovery.addParameter("version", "1.0.0");

        LOGGER.info("Starting auto discovery!");
        autoDiscovery.start();

        //At this point you can put in your application's logic
        LOGGER.info("I'm going to wait for " + SECONDS
                    + " seconds for other peers.");
        countdown();

        //Before you close your program, stop the auto discovery thread
        autoDiscovery.stop();

        LOGGER.info("Bye Bye!");
    }

    private static void countdown() throws InterruptedException {
        int counter = SECONDS;

        while (counter > 0) {
            counter--;
            System.out.println(counter + " seconds remaining...");
            Thread.sleep(1000);
        }
    }
}

That's all folks!


Related

Wiki: Home

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.