package org.kne.cloud.network;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.*;
import java.util.concurrent.locks.LockSupport;

import org.kne.cloud.network.klalb.CannotAssociateException;
import org.kne.cloud.network.klalb.KLALBVirtualSocket;
import org.kne.io.Task;
public class SocketBridge extends Task{
	protected Socket a;
	protected Socket b;
	protected StreamBridge bridgeAB;
	protected StreamBridge bridgeBA;
	public StreamBridge getBridgeAB() {
		return bridgeAB;
	}
	public StreamBridge getBridgeBA() {
		return bridgeBA;
	}
	public SocketBridge(Socket a, Socket b) throws IOException {
		super();
		this.a = a;
		this.b = b;
		createStreamBridge();
	}
	protected void createStreamBridge() throws IOException {
		bridgeAB = new StreamBridge(a.getInputStream(), b.getOutputStream());
		bridgeBA = new StreamBridge(b.getInputStream(), a.getOutputStream());
	}
	@Override
	protected void runTask() {
		try {
		
			Thread ta=bridgeAB.runAtNewThread("SocketBridge A->B thread");
			Thread tb=bridgeBA.runAtNewThread("SocketBridge B->A thread");
			while((ta.isAlive()||tb.isAlive())&&(!a.isClosed())&&(!b.isClosed())) {
				LockSupport.parkNanos(1000000L);
			}
		
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			//new Exception().printStackTrace();
			try {
				a.close();
			} catch (IOException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
			try {
				b.close();
			} catch (IOException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
		}
	}
	public Socket getA() {
		return a;
	}
	public Socket getB() {
		return b;
	}
	/*protected OutputStream getBOUT() throws IOException {
		return b.getOutputStream();
	}
	protected InputStream getBIN() throws IOException {
		return b.getInputStream();
	}
	protected OutputStream getAOUT() throws IOException {
		return a.getOutputStream();
	}
	protected InputStream getAIN() throws IOException {
		return a.getInputStream();
	}*/
	
}
