1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| public void server() { try { ServerSocketChannel ssc = ServerSocketChannel.open(); ssc.configureBlocking(false);
ssc.bind(new InetSocketAddress(8899));
Selector selector = Selector.open(); ssc.register(selector, SelectionKey.OP_ACCEPT);
while (selector.select() > 0) { Iterator<SelectionKey> its = selector.selectedKeys().iterator(); while (its.hasNext()) { SelectionKey sk = its.next(); if (sk.isAcceptable()) { SocketChannel sc = ssc.accept(); sc.configureBlocking(false); sc.register(selector, SelectionKey.OP_READ); } else if (sk.isReadable()) { SocketChannel sc = (SocketChannel) sk.channel(); ByteBuffer buf = ByteBuffer.allocate(1024); int len; while ((len = sc.read(buf)) > 0) { buf.flip(); System.out.println(new String(buf.array(), 0, len)); try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } buf.clear(); } } its.remove(); } } } catch (IOException e) { e.printStackTrace(); }
}
|