Selector流程原理
Selector要点
Selector 常用方法
采用Channel和ByteBuffer,Selector,手写tomcat
//采用NIO,Channel和ByteBuffer,Selector
public class tomcatSelector {
public static final String SEPARATOR = "\r\n";
//源码注释:requested maximum length of the queue of incoming connections.
//BACK_LOG影响的accept队列大小
public static final int BACK_LOG = 1024;
public static void main(String[] args) throws Exception {
ServerSocketChannel serverChannel = ServerSocketChannel.open();
serverChannel.configureBlocking(false);
serverChannel.bind(new InetSocketAddress(10000), BACK_LOG);
Selector selector = Selector.open();
serverChannel.register(selector, SelectionKey.OP_ACCEPT);
System.out.println("启动服务器");
for (; ; ) {
selector.select();
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = selectionKeys.iterator();
System.out.println("----------------------");
while (iterator.hasNext()) {
SelectionKey next = iterator.next();
if (next.isAcceptable()) {
ServerSocketChannel serverChannelIn = (ServerSocketChannel) next.channel();
SocketChannel acceptChannel = serverChannelIn.accept();
System.out.println(acceptChannel.getRemoteAddress());
acceptChannel.configureBlocking(false);
acceptChannel.register(selector, SelectionKey.OP_WRITE);
System.out.println(1);
}
if (next.isWritable()) {
System.out.println(2);
SocketChannel channel = (SocketChannel) next.channel();
try {
//模拟在做事
Thread.sleep(500);
channel.write(ByteBuffer.wrap(HttpRequest().getBytes()));
} catch (Exception e) {
//e.printStackTrace();
}
}
iterator.remove();
}
}
}
public static String HttpRequest() {
String str = "<h1>tomcat</h1>";
StringBuilder builder = new StringBuilder();
builder.append("HTTP/1.1 200 OK").append(SEPARATOR);
builder.append("Connection: Close").append(SEPARATOR);
builder.append("Content-Type: text/html;charset=utf-8").append(SEPARATOR);
builder.append("Content-Length: " + str.length()).append(SEPARATOR);
builder.append(SEPARATOR);
builder.append(str);
return builder.toString();
}
}