package jp.hasc.hupclient;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketTimeoutException;
import java.nio.charset.Charset;

/* Test Cilent for HASC UDP Proxy
 * 
 * 
 * */
public class HUPTestClient implements Runnable {
	
	private static final int DEFAULT_UDP_PORT = 6666;
	private static final int UDP_TIMEOUT = 2000;
	private static final String ServerIP = "133.6.157.35"; // uclab server address.

	private int port_=DEFAULT_UDP_PORT;
	private DatagramSocket socket_;

	@Override
	public void run() {
		
		Charset charset = Charset.forName("UTF-8");
		byte[] buff = new byte[1024];
		DatagramPacket packet = new DatagramPacket(buff, buff.length);
		try {
			socket_ = new DatagramSocket(port_);
//			socket_ = new DatagramSocket();
					
			DatagramPacket sdpacket = new DatagramPacket(buff, buff.length);
			sdpacket.setAddress(InetAddress.getByName(ServerIP));
			sdpacket.setPort(9999);
			
			System.out.println("Sending UDP packets ");
			socket_.send(sdpacket);

//			System.out.println("Receiving UDP packets on port " + port_ + ".");
			System.out.println("Receiving UDP packets on port " + socket_.getLocalPort() + ".");
					
//			socket_.setSoTimeout(UDP_TIMEOUT);
			while (true) {
				try{
					socket_.receive(packet);
					byte[] data = packet.getData();
					String s = new String(data, packet.getOffset(), packet.getLength(),
							charset);
					System.out.println("Receive:"+s);
//					outputMessage(s);
				}catch(SocketTimeoutException ex) {
					//LOG.debug("timeout");
					System.out.println("Err");
					ex.printStackTrace();
				}
			}
		} catch (IOException ex) {
//			LOG.warn("IOException",ex);
		} finally {
			if (socket_!=null) socket_.close();
			socket_=null;
//			outputMessage(SignalMessage.END);
//			LOG.info("closed.");
		}
	}

	public int getPort() {
		return port_;
	}

	public void setPort(int udpPort) {
		port_ = udpPort;
	}
	
	public static void main(String [] args){
		HUPTestClient huptc = new HUPTestClient();
		
		Thread th = new Thread(huptc);
		th.start();
		
	}
}
