1 36 37 import java.io.*; 38 import java.nio.*; 39 import java.nio.channels.*; 40 41 53 class ChannelIO { 54 55 protected SocketChannel sc; 56 57 62 protected ByteBuffer requestBB; 63 static private int requestBBSize = 4096; 64 65 protected ChannelIO(SocketChannel sc, boolean blocking) 66 throws IOException { 67 this.sc = sc; 68 sc.configureBlocking(blocking); 69 } 70 71 static ChannelIO getInstance(SocketChannel sc, boolean blocking) 72 throws IOException { 73 ChannelIO cio = new ChannelIO(sc, blocking); 74 cio.requestBB = ByteBuffer.allocate(requestBBSize); 75 76 return cio; 77 } 78 79 SocketChannel getSocketChannel() { 80 return sc; 81 } 82 83 87 protected void resizeRequestBB(int remaining) { 88 if (requestBB.remaining() < remaining) { 89 ByteBuffer bb = ByteBuffer.allocate(requestBB.capacity() * 2); 91 requestBB.flip(); 92 bb.put(requestBB); 93 requestBB = bb; 94 } 95 } 96 97 105 boolean doHandshake() throws IOException { 106 return true; 107 } 108 109 118 boolean doHandshake(SelectionKey sk) throws IOException { 119 return true; 120 } 121 122 126 int read() throws IOException { 127 130 resizeRequestBB(requestBBSize/20); 131 return sc.read(requestBB); 132 } 133 134 137 ByteBuffer getReadBuf() { 138 return requestBB; 139 } 140 141 144 int write(ByteBuffer src) throws IOException { 145 return sc.write(src); 146 } 147 148 151 long transferTo(FileChannel fc, long pos, long len) throws IOException { 152 return fc.transferTo(pos, len, sc); 153 } 154 155 163 boolean dataFlush() throws IOException { 164 return true; 165 } 166 167 175 boolean shutdown() throws IOException { 176 return true; 177 } 178 179 182 void close() throws IOException { 183 sc.close(); 184 } 185 186 } 187 | Popular Tags |