package bg.testing.network; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.Iterator; import java.util.Set; public class SelectorTest { /** * @param args */ public static void main(String[] args) { new Thread(new Server()).start(); new Thread(new Client()).start(); } static class Server implements Runnable { Selector sel; @Override public void run() { try { ServerSocketChannel server = ServerSocketChannel.open(); server.socket().bind(new InetSocketAddress(5555)); server.configureBlocking(false); sel = Selector.open(); server.register(sel, SelectionKey.OP_ACCEPT); boolean running = true; while(running) { int count = sel.select(); if(sel.isOpen() && count > 0) { Set keyset = sel.selectedKeys(); synchronized(keyset) { Iterator i = keyset.iterator(); while(i.hasNext()) { SelectionKey key = i.next(); i.remove(); processKey(key); } } } else if(!sel.isOpen()) running = false; } } catch (IOException e) { e.printStackTrace(); } } private void processKey(SelectionKey key) { if(key.isValid() && key.isAcceptable()) { try { SocketChannel chan = ((ServerSocketChannel)key.channel()).accept(); chan.configureBlocking(false); chan.register(sel, SelectionKey.OP_READ); } catch (IOException e) { e.printStackTrace(); } } if(key.isValid() && key.isReadable()) { System.out.println("Read starting..."); SocketChannel chan = (SocketChannel) key.channel(); ByteBuffer buff = ByteBuffer.allocate(1024); try { while((chan.read(buff))>=0) { buff.flip(); System.out.println("read some"); buff.clear(); } chan.close(); System.out.println("Read complete"); } catch (IOException e) { e.printStackTrace(); } } } } static class Client implements Runnable { @Override public void run() { try { SocketChannel chan = SocketChannel.open(); chan.connect(new InetSocketAddress("localhost", 5555)); while(!chan.finishConnect()); ByteBuffer buff = ByteBuffer.allocate(1024); for(int i=0;i<1000;i++) { buff.flip(); chan.write(buff); buff.compact(); } chan.close(); } catch (IOException e) { e.printStackTrace(); } } } }