import java.io.IOException; import java.net.Socket; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.util.Iterator; import java.util.LinkedList; import java.util.Set; import java.util.Vector; public class ReaderThread extends Thread { private static final int BUFFER_SIZE = 16; private Selector readSelector = null; private ByteBuffer readBuffer; private Charset ascii = Charset.forName("US-ASCII"); private CharsetDecoder asciiDecoder = ascii.newDecoder(); private LinkedList connections = null; public ReaderThread(LinkedList connections) throws IOException { super(); this.connections = connections; this.readSelector = Selector.open(); this.readBuffer = ByteBuffer.allocateDirect(BUFFER_SIZE); } @Override public void run() { while (true) { try { SocketChannel channel; while ( (connections.size() > 0) && (null != (channel = connections.removeFirst())) ) { channel.configureBlocking(false); channel.register(readSelector, SelectionKey.OP_READ, new StringBuffer()); } int keysReady = readSelector.select(); // blocking if (keysReady > 0) { Set readyKeys = readSelector.selectedKeys(); for (SelectionKey key : readyKeys ) { readyKeys.remove(key); readRequest(key); } } } catch (Exception e) { e.printStackTrace(); } } } protected void readRequest(SelectionKey key) throws Exception { SocketChannel incomingChannel = (SocketChannel) key.channel(); try { incomingChannel.read(readBuffer); readBuffer.flip(); String result = asciiDecoder.decode(readBuffer).toString(); readBuffer.clear(); System.out.print(result); CharBuffer chars = CharBuffer.allocate(1); chars.put("#"); chars.flip(); ByteBuffer writeBuffer = ascii.newEncoder().encode(chars); incomingChannel.write(writeBuffer); } catch (IOException e) { e.printStackTrace(); } } public Selector getReadSelector() { return readSelector; } }