/*********************************************************************
 * Reception.java
 * org.omni.commons.clerk
 * 
 * E-mail:omni_wx@163.com
 ********************************************************************/
package org.omni.commons.clerk;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import org.omni.commons.lang.ThreadService;

// TODO: Auto-generated Javadoc
/**
 * The Class Reception.
 *
 * @author 王兴
 * @since v1.0
 * @date Aug 7, 2015
 */
public class Reception extends ThreadService {
	
	/** server. */
	private ServerSocket server;

	/**
	 * 构造一个新的 reception 对象.
	 */
	public Reception() {
		try {
			server = new ServerSocket(10000);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	* <p>Title: onStop</p>
	* <p>Description: </p>
	* @throws Throwable
	* @see org.omni.commons.lang.ThreadService#onStop()
	*/
	/* (non-Javadoc)
	 * @see org.omni.commons.lang.ThreadService#onStop()
	 */
	@Override
	protected void onStop() throws Throwable {
		if (!server.isClosed()) {
			server.close();
		}
	}

	/**
	* <p>Title: onRun</p>
	* <p>Description: </p>
	* @throws Throwable
	* @see org.omni.commons.lang.ThreadService#onRun()
	*/
	/* (non-Javadoc)
	 * @see org.omni.commons.lang.ThreadService#onRun()
	 */
	@Override
	protected void onRun() throws Throwable {
		Socket socket = server.accept();
		byte[] len = new byte[4];
		socket.getInputStream().read(len);
		int length = Integer.valueOf(new String(len).trim()).intValue();
		byte[] classBytes = new byte[length];
		socket.getInputStream().read(classBytes);
		new Thread(new Executor(classBytes, socket), "JavaClassExecutor").start();
	}

	/**
	* <p>Title: onStart</p>
	* <p>Description: </p>
	* @throws Throwable
	* @see org.omni.commons.lang.ThreadService#onStart()
	*/
	/* (non-Javadoc)
	 * @see org.omni.commons.lang.ThreadService#onStart()
	 */
	@Override
	protected void onStart() throws Throwable {
		// TODO Auto-generated method stub
		System.out.println("Clerk Reception Service is starting!");
	}
}
