gpt4 book ai didi

java - 为什么没有收到另一个http请求?

转载 作者:行者123 更新时间:2023-12-02 06:58:19 24 4
gpt4 key购买 nike

我正在使用 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)为什么一开始会额外收到一个accept事件?2)为什么没有收到第二个http请求?连接被接受,其 SocketChannel 正在选择器中注册。但未收到请求正文。我知道生成了很多“空”读取事件,但它们都没有带来请求正文。

最佳答案

  1. 您有三个接受事件。
  2. 可能是因为您尚未回复第一个。
  3. “空”读取事件可能已关闭,您忽略了它。

尝试修复所有这些问题并重新测试。当你不乖的时候,你不能指望对方乖乖的。

关于java - 为什么没有收到另一个http请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17012915/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com