Package network

Source Code of network.HostUDPServer

package network;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.util.Properties;

import util.Constants;
import util.Globals;

public class HostUDPServer extends Thread {
 
  protected DatagramSocket socket = null;
 
  public HostUDPServer()
  {
        try
        {
            // Leer el archivo almacenado
            Properties prop = new Properties();
            prop.load(ClassLoader.getSystemResource(Constants.PROPERTIES_PREFERENCES).openStream());
           
            // Recuperar el nombre e IP
            Globals.localIP = (String)prop.get(Constants.PROP_PREFERENCE_HOSTIP);
            Globals.localHostName = (String)prop.get(Constants.PROP_PREFERENCE_HOSTNAME);
           
            System.out.println( " Host properties: " + Globals.localHostName + "(" + Globals.localIP + ")" );
        }
        catch (Exception e)
        {
          e.printStackTrace();
        }
  }

  public void run() {
   
      while (Globals.running)
      {
          try {
           
          // delay inicial antes de empezar el envio de estado
          sleep(Constants.FIRST_REFRESH_TIME_MS);

          // enviar status actual
          sendPing(null);

              // actualizar el status cada cierto intervalo de tiempo
                sleep(Constants.STATUS_REFRESH_TIME_MS - Constants.FIRST_REFRESH_TIME_MS);
          }
            catch (InterruptedException e) { e.printStackTrace(); }
          catch (IOException e) { e.printStackTrace(); }
          catch (Exception e) { e.printStackTrace(); }
      }
    try {
      sendPing(new Boolean(false));
      if (socket != null)
        socket.close();
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
  }
 
 
  protected void sendPing(Boolean status) throws Exception
  {
    int online = -1;
   
    if (status == null)
      online = Globals.online ? 1 : 0;
    else
      online = status ? 1 : 0;
   
    // enviar mi estado actual
        byte[] buf = new byte[256];
        String dString = null;
        dString = Globals.localHostName + "::" + Globals.localIP + "::" + online + "::";
        buf = dString.getBytes();

        InetAddress group = InetAddress.getByName(Constants.GROUP_IP);
        DatagramPacket packet;
        packet = new DatagramPacket(buf, buf.length, group, Constants.PORT_UDP);
        MulticastSocket socket = new MulticastSocket(Constants.PORT_UDP);
        socket.send(packet);
  }
 
}
TOP

Related Classes of network.HostUDPServer

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.