Mega Code Archive

 
Categories / Java Tutorial / Network
 

Using a Selector to Manage Non-Blocking Server Sockets

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; public class Main {   public static void main(String[] argv) throws Exception {     Selector selector = Selector.open();     ServerSocketChannel ssChannel1 = ServerSocketChannel.open();     ssChannel1.configureBlocking(false);     ssChannel1.socket().bind(new InetSocketAddress(80));     ServerSocketChannel ssChannel2 = ServerSocketChannel.open();     ssChannel2.configureBlocking(false);     ssChannel2.socket().bind(new InetSocketAddress(81));     ssChannel1.register(selector, SelectionKey.OP_ACCEPT);     ssChannel2.register(selector, SelectionKey.OP_ACCEPT);     while (true) {       selector.select();       Iterator it = selector.selectedKeys().iterator();       while (it.hasNext()) {         SelectionKey selKey = (SelectionKey) it.next();         it.remove();         if (selKey.isAcceptable()) {           ServerSocketChannel ssChannel = (ServerSocketChannel) selKey.channel();           SocketChannel sc = ssChannel.accept();           ByteBuffer bb =ByteBuffer.allocate(100);           sc.read(bb);                    }       }     }   } }