package org.kne.cloud.network; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.*; import java.nio.channels.SocketChannel; import org.kne.cloud.network.klalb.KLALBVirtualSocket; import org.kne.cloud.network.klalb.KLALBVirtualSocketChannel; import org.kne.io.Task; public class SocketChannelBridge extends Task{ protected SocketChannel a; protected SocketChannel b; protected StreamChannelBridge bridgeAB; protected StreamChannelBridge bridgeBA; public StreamChannelBridge getBridgeAB() { return bridgeAB; } public StreamChannelBridge getBridgeBA() { return bridgeBA; } public SocketChannelBridge(SocketChannel a, SocketChannel b) throws IOException { super(); this.a = a; this.b = b; createStreamChannelBridge(); } protected void createStreamChannelBridge() throws IOException { bridgeAB = new StreamChannelBridge(a, b); bridgeBA = new StreamChannelBridge(b, a); } @Override protected void runTask() { try { if(a instanceof KLALBVirtualSocketChannel) { ((KLALBVirtualSocketChannel) a).associateSocketChannel(b); }else if(b instanceof KLALBVirtualSocketChannel){ ((KLALBVirtualSocketChannel) b).associateSocketChannel(a); }else { bridgeAB.runAtNewThread("SocketBridge A->B thread"); bridgeBA.runAtNewThread("SocketBridge B->A thread"); bridgeAB.waitfortask(); bridgeBA.waitfortask(); } } 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 SocketChannel getA() { return a; } public SocketChannel 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(); }*/ }