public class NioMultiplexingEchoServer { public static void main(String[] args) throws IOException { final int ports = 8; ServerSocketChannel[] serverSocketChannels = new ServerSocketChannel[ports]; Selector selector = Selector.open(); for (int p = 0; p < ports; p++) { ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannels[p] = serverSocketChannel; serverSocketChannel.configureBlocking(false); serverSocketChannel.bind(new InetSocketAddress("localhost", 7000 + p)); serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); } while (active) { selector.select(); // blocking Iterator<SelectionKey> keysIterator = selector.selectedKeys().iterator(); while (keysIterator.hasNext()) { SelectionKey key = keysIterator.next(); if (key.isAcceptable()) { accept(selector, key); } if (key.isReadable()) { keysIterator.remove(); read(selector, key); } if (key.isWritable()) { keysIterator.remove(); write(key); } } } for (ServerSocketChannel serverSocketChannel : serverSocketChannels) { serverSocketChannel.close(); } } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter