import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class UDPServer {

	public static void main(String[] args) {
		DatagramSocket serverSocket = null;
		try {
			serverSocket = new DatagramSocket(9050);
		} catch (SocketException e) {
			e.printStackTrace();
		}
		System.out.println("Server Started!!");
		while (true) {
			
			byte[] receiveData = new byte[1024];
			byte[] sendData = new byte[1024];
			int receivedPacketsCount = 0;
			DatagramPacket receivePacket=null;
			int port=0;
			InetAddress IPAddress=null;
			try{
			serverSocket.setSoTimeout(0);
			}
			catch (Exception e) {
			}
			while (true) {
				try {
					 receivePacket = new DatagramPacket(
							receiveData, receiveData.length);
					serverSocket.receive(receivePacket);
					 IPAddress = receivePacket.getAddress(); 
					port = receivePacket.getPort();
					
					serverSocket.setSoTimeout(10000);
					receivedPacketsCount++;
					System.out.println("Received: " + receivedPacketsCount);
				} catch (Exception c) {
					break;
				}

			}
			System.out.println("TOTAL Received: " + receivedPacketsCount);
			
			//send number back
         
            sendData = Integer.toString(receivedPacketsCount).getBytes(); 
            DatagramPacket sendPacket=new DatagramPacket(sendData, sendData.length, IPAddress, port);
            for (int i = 0; i < 10; i++) {
            	try {
					serverSocket.send(sendPacket);
				} catch (IOException e) {
					e.printStackTrace();
				} 	
			}
            System.out.println("Send back total");
            try {
				Thread.sleep(10000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            for (int i = 0; i < 100; i++) {
            	try {
            		sendData = "secret".getBytes(); 
            		sendPacket=new DatagramPacket(sendData, sendData.length, IPAddress, port);
					serverSocket.send(sendPacket);
				} catch (IOException e) {
					e.printStackTrace();
				} 	
			}
            System.out.println("Finished Send for download");

		}
	}
}
