简单的回声服务器,侦听传入的流连接并回显所读取的内容。
import java.net.InetSocketAddress; import java.net.ServerSocket; /* 来自 *时代Java公众号*/ import java.nio.ByteBuffer; import java.nio.channels.SelectableChannel; 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 {/**来 自 nowjava.com - 时代Java**/ public static void main(String[] argv) throws Exception { int port = 5555; System.out.println("Listening on port " + port); ServerSocketChannel serverChannel = ServerSocketChannel.open(); ServerSocket serverSocket = serverChannel.socket(); Selector selector = Selector.open(); serverSocket.bind(new InetSocketAddress(port)); serverChannel.configureBlocking(false); serverChannel.register(selector, SelectionKey.OP_ACCEPT); while (true) { int n = selector.select(); if (n == 0) { continue; // nothing to do } Iterator it = selector.selectedKeys().iterator(); while (it.hasNext()) { SelectionKey key = (SelectionKey) it.next(); if (key.isAcceptable()) { ServerSocketChannel server = (ServerSocketChannel) key.channel(); SocketChannel channel = server.accept(); registerChannel(selector, channel, SelectionKey.OP_READ); channel.write(ByteBuffer.wrap("Hi there!\r\n".getBytes())); } if (key.isReadable()) { readDataFromSocket(key); } it.remove(); } } } protected static void registerChannel(Selector selector, SelectableChannel channel, int ops) throws Exception { if (channel == null) { return; // could happen } channel.configureBlocking(false); channel.register(selector, ops); } protected static void readDataFromSocket(SelectionKey key) throws Exception { SocketChannel socketChannel = (SocketChannel) key.channel();