package net.bakingpowder.jspl.tcprelay.distributed.recieveRelay;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;

/**
 * @author Tomoo D. Mizukami/JAIST/Softbank Publishing Inc.
 * 
 * This class is multi-thread class for buffer-interchange-function.
 */
public class RecieveInput2Output implements Runnable {
	private InputStream in = null;
	private OutputStream out = null;
	private RecieveConnectControl cc = null;
	private byte buffer[] = null;
	private static int BUFFER_SIZE = 4096;
	private boolean stopper = false;
	
	public synchronized void stopd(){
		this.stopper = true;
	}
	
	/**
	 * @param in
	 *            InputStream
	 * @param out
	 *            OutputStream
	 * @param cm
	 *            ConnectControl
	 */
	public RecieveInput2Output(InputStream in, OutputStream out, RecieveConnectControl cc) {
		this.in = in;
		this.out = out;
		this.cc = cc;
		buffer = new byte[BUFFER_SIZE];

		t = new Thread(this);
		t.start();
	}
	private Thread t;

	public void run()  {
		try {
			int bytesRead = 0;

			LOOP1 : while (!this.stopper) {
				
				t.setPriority(10);
				if ((bytesRead = in.read(buffer, 0, BUFFER_SIZE)) == -1)
					break;

				out.write(buffer, 0, bytesRead);
				
				t.setPriority(1);
				Thread.sleep(5);
				
				
			}

		} catch (IOException e) {
			//ignore
		} catch (InterruptedException e) {
			//ignore
			System.out.println("Recieve TCPRelay Error");
		}
		cc.ThreadArrivedEnd(this);
	}
}