package org.kne.cloud.network; import java.io.*; import java.nio.ByteBuffer; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import java.util.Objects; import java.util.UUID; import org.kne.io.Task; public class ChannelBridge extends Task{ protected ReadableByteChannel in; protected WritableByteChannel out; protected int blocksize=65535; protected long delay=0; public ChannelBridge(ReadableByteChannel in, WritableByteChannel out) { super(); Objects.requireNonNull(in); Objects.requireNonNull(out); this.in = in; this.out = out; } @Override public void runTask() { //FileOutputStream fos=null; try { //fos=new FileOutputStream(UUID.randomUUID()+".txt"); ByteBuffer b=ByteBuffer.allocateDirect(blocksize); while (in.read(b)!=-1) { b.flip(); out.write(b); b.clear(); if(delay>0) { try { Thread.sleep(delay); } catch (InterruptedException e) { e.printStackTrace(); } }else { Thread.yield(); } } } catch (IOException e) { e.printStackTrace(); }finally { /*if(fos!=null) try { fos.close(); } catch (IOException e1) { e1.printStackTrace(); }*/ try { if(in!=null) in.close(); } catch (IOException e) { e.printStackTrace(); } try { if(in!=null) out.close(); } catch (IOException e) { e.printStackTrace(); } } } public int getBlocksize() { return blocksize; } public void setBlocksize(int blocksize) { this.blocksize = blocksize; } public long getDelay() { return delay; } public void setDelay(long delay) { this.delay = delay; } public void runAtNewThread() { runAtNewThread("StreamBridge thread"); } public void runAtNewThread(String name) { ThreadTool.makeVThreadIfSupport(name, this).start(); } }