package test;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.ByteBuffer;

public class Client {
	
	protected Socket socket;
	protected InputStream in;
	protected OutputStream out;
	
	public Client(String host, int port) throws IOException {
		this.socket = new Socket(host, port);
		socket.setTcpNoDelay(true);
		socket.setSoLinger(true, 10);
		
		InputStream tmpIn = socket.getInputStream();
		OutputStream tmpOut = socket.getOutputStream();
		
	    tmpOut.write(1); //
	    tmpOut.write(1); // 
	    ByteBuffer buffer = ByteBuffer.allocate(4); //
	    tmpOut.write( buffer.putInt(1).array() ); //
	    tmpOut.flush();
	    
	    int tmpRet = tmpIn.read();
	    //if (tmpRet == 0) {
	    	this.in = new BufferedInputStream(tmpIn);  // socket.inputStream.
	        this.out = new BufferedOutputStream(tmpOut);  // local.outputStream.
	    //}
	}
	
	public void foo() {
		try{
			int len;
			int count = 0;
			byte[] data = new byte[16384];
			while((len = in.read(data)) != -1){
				System.out.println(len);
				System.out.println(new String(data).substring(0, 20));
				if (count++ == 0)
					Thread.sleep(3 * 60 * 1000);
			}
			System.out.println("Normal exit.");
		} catch (Throwable e) {
			e.printStackTrace();
		}finally{
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				out = null;
			}
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				in = null;
			}
			if (socket != null) {
				try {
					socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				socket = null;
			}
		}
	}

	public static void main(String[] args) {
		
		String host = "127.0.0.1";
		if (args.length > 0) {
			host = args[0];
		}
		
		int port = 44142;
		if (args.length > 1) {
			port = Integer.valueOf(args[1]);
		}
		
		Client client;
		try {
			client = new Client(host, port);
			client.foo();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
