Download Latest Version NetworkService1.0.0.1_2.zip (233.2 kB)
Email in envelope

Get an email when there's a new version of NetworkService

Home / NetworkService1.0.0.3
Name Modified Size InfoDownloads / Week
Parent folder
NetworkService1.0.0.3.zip 2014-07-06 1.2 MB
readme.txt 2014-07-06 2.7 kB
Totals: 2 Items   1.2 MB 0
public class HowToUseNetworkService {

    public static void main(String[] args) throws Exception {

        //create a new instance of NetworkService

        NetworkService ns = new NetworkService(new ClientInterfaceImpl());

        //register a ClientStateChangeListener to recieve notifications
        //about group members state.

        ns.addClientStateChangeListener(new ClientStateChangeListenerImpl());

        //start the service.
        ns.startService(false);

        Random gen = new Random();

        Thread.sleep(gen.nextInt(3000));

        //send a message to all group members.


        ns.multicast("hello all!");

        //send a message to one of the group members.

  
        ClientID agroupmember = ns.getClientsTable().values().iterator().next();


        ns.sendMessage("hello "+agroupmember.name(),agroupmember);

        Thread.sleep(gen.nextInt(1000));

           ns.multicast("bye all!");


        //stop the service

        ns.stopService();

    }

    static class ClientInterfaceImpl implements ClientInterface {

        public ClientInterfaceImpl() {
        }

        public void publicMessageReceived(String msg, ClientID from) {
            System.out.println(from.name()+" says: "+msg);
        }

        public void privateMessageReceived(String msg, ClientID from) {
            System.out.println(from.name()+" says: "+msg);
        }

        public void clientConnected(SocketStreamRW connection) {
            //accept TCP connection here.
         //See: NetworkService.connect(ClientID);
        }



        public void errMessage(String error, String from) {
            //used for debugging
        }

        public void infMessage(String info, String from) {
              //used for debugging
        }
    }

    private static class ClientStateChangeListenerImpl implements ClientStateChangeListener {

        public ClientStateChangeListenerImpl() {
        }

        public void clientStateChanged(ClientStateChangeEvent evt) {
            String name = evt.getClient().name();
            String host = evt.getClient().hostName();
            int state = evt.getNewState();
            String s;
            switch (state) {
                case ClientStateChangeEvent.ON:
                    s = "on";
                    break;
                case ClientStateChangeEvent.OFF:
                    s = "off";
                    break;
                default:
                    s = "unknown";
            }

            System.out.println(name + " on " + host + " is " + s);
        }
    }


}
Source: readme.txt, updated 2014-07-06