我正在使用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正在选择器中注册。但是没有收到请求正文。我知道生成了许多“空”读事件但没有一个带来请求体。
答案 0 :(得分:1)
尝试修复所有这些并重新测试。当你不是时,你不能指望同伴表现自己。
答案 1 :(得分:1)
为什么我在开始时会收到额外的接受事件?
为什么没有收到第二个http请求?
在IE
中检查此行为