import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

/**
 * @author Michalis Katsarakis
 * @author Kostas Magoutis
 * @version 25 May 2013
 * @see http://www.csd.uoc.gr/~hy335b/
 * 
 * <p>Joins a multicast group and echoes all data it receives from the group to its stdout.</p>
 */
public class MulticastClient {

	public static final int HELLO_PORT = 12345;
	public static final String HELLO_GROUP= "ff00:0:0:0:0:0:e100:25";
	public static final int BUFFER_LENGTH = 1024;

	public static void main(String[] args) throws Exception {
		
		/* Create a multicast socket and bind it to port 'HELLO_PORT'. */
		final MulticastSocket udpMulticastSocket = new MulticastSocket(HELLO_PORT);
		
		/* Set up multicast group address. */
		final InetAddress groupAddress = InetAddress.getByName(HELLO_GROUP);
		
		/* Send an IGMP Membership report to the local multicast router */
		udpMulticastSocket.joinGroup(groupAddress);
		
		System.out.println("Multicast Client running on "+InetAddress.getLocalHost().getHostName()+". Socket bound and group joined.\n");
		
		/* Now we are ready to receive packets */
		byte[] receiveBuffer = new byte[BUFFER_LENGTH];
		while (true) {
			DatagramPacket udpPacket = new DatagramPacket(receiveBuffer, receiveBuffer.length);
			udpMulticastSocket.receive(udpPacket);
			String payload = new String(udpPacket.getData(), 0, udpPacket.getLength());
			System.out.println("Received UDP packet with payload = '"+payload+"'.");
		}
		
	}

}
