NIO ServerSocketChannel 例子

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
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 EchoNioSocketServer {
	public static void main(String[] args) throws IOException {
		ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
		serverSocketChannel.configureBlocking(false);
		ServerSocket socket = serverSocketChannel.socket();
		socket.bind(new InetSocketAddress(8080));
		final Selector sel = Selector.open();
		serverSocketChannel.register(sel, SelectionKey.OP_ACCEPT);
		while (true) {
			sel.select();
			Iterator<SelectionKey> iterator = sel.selectedKeys().iterator();
			while (iterator.hasNext()) {
				SelectionKey key = iterator.next();
				if (key.isAcceptable()) {
					SocketChannel socketChannel = ((ServerSocketChannel) key.channel()).accept();
					socketChannel.configureBlocking(false);
					socketChannel.register(sel, SelectionKey.OP_READ, null);
				} else if (key.isReadable()) {
					ByteBuffer buf = ByteBuffer.allocate(512);
					SocketChannel socketChannel = (SocketChannel) key.channel();
					socketChannel.read(buf);
					key.interestOps(key.interestOps() | SelectionKey.OP_WRITE);
					key.attach(buf.flip());
				} else if (key.isWritable()) {
					SocketChannel socketChannel = (SocketChannel) key.channel();
					socketChannel.write((ByteBuffer) key.attachment());
					key.interestOps(key.interestOps() & (~SelectionKey.OP_WRITE));
				}
				iterator.remove();
			}
		}
	}
}



你可能感兴趣的:(NIO ServerSocketChannel 例子)