package artistmetrics;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MulticastSocket;

public class ServerFinder extends Thread
{
    LoginForm form;
    
    ServerFinder(LoginForm form)
    {
        this.form = form;
    }

    public void run()
    {
        String MULTICAST_ADDR = "224.0.0.100";
        int LISTEN_PORT = 31335;
        int REPLY_PORT = 31336;
        
        try
        {
            //Set up the server to listen for the repsonse.
            byte[] serverAddr = new byte[2048];
            DatagramPacket addrDatagram = new DatagramPacket(serverAddr, serverAddr.length);
            MulticastSocket receivingSocket = new MulticastSocket(REPLY_PORT); // must bind receive side
            receivingSocket.joinGroup(InetAddress.getByName(MULTICAST_ADDR));

            DatagramSocket socket = new DatagramSocket();
            byte[] b = new byte[2];
            DatagramPacket dgram;

            dgram = new DatagramPacket(b, b.length, InetAddress.getByName(MULTICAST_ADDR), LISTEN_PORT);

            socket.send(dgram);
            
            while(true)
            {
            	receivingSocket.receive(addrDatagram);
            	form.addServer(new String(serverAddr));
            }
        }
        catch(Exception e)
        {
            System.out.println("Exception: " + e.toString());
        }
    }
}
