我正在使用 Java NIO 编写一个简单的 HTTP 服务器,但很早就陷入了沉默。我有以下代码:
Selector accept = Selector.open();
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.configureBlocking(false);
InetAddress lh = InetAddress.getByName("127.0.0.1");
InetSocketAddress isa = new InetSocketAddress(lh, port);
ssc.socket().bind(isa);
SelectionKey acceptKey = ssc.register(accept,
SelectionKey.OP_ACCEPT);
while (accept.select() > 0) {
Set<SelectionKey> readyKeys = accept.selectedKeys();
Iterator<SelectionKey> i = readyKeys.iterator();
while (i.hasNext()) {
SelectionKey sk = i.next();
if (sk.isAcceptable()) {
System.out.println("Is acceptable");
ssc = (ServerSocketChannel) sk.channel();
SocketChannel sc = ssc.accept();
sc.configureBlocking(false);
sc.register(accept, SelectionKey.OP_READ);
System.out.println("Registered new SocketChannel");
}
if (sk.isReadable()) {
SocketChannel sc = (SocketChannel) sk.channel();
ByteBuffer buffer = ByteBuffer.allocate(20000);
buffer.clear();
int bytesRead = sc.read(buffer);
buffer.flip();
while (buffer.hasRemaining()) {
System.out.print((char) buffer.get());
}
buffer.clear();
}
i.remove();
}
}
现在,如果我在浏览器中打开两个选项卡并导航到 localhost:8080,这将是应用程序的输出:
Is acceptable
Registered new SocketChannel
Is acceptable
Registered new SocketChannel
GET / HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
User-Agent: Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Is acceptable
Registered new SocketChannel
现在我有两个问题:1)为什么我一开始会得到一个额外的接受事件?2)为什么没有收到第二个http请求?连接被接受,它的 SocketChannel 正在选择器中注册。但是没有收到请求正文。我知道生成了许多“空”读取事件,但它们都没有带来请求正文。