gpt4 book ai didi

http - 如何从 netty 中的 HTTP 服务器请求处理程序正确调用 HTTP 客户端?

转载 作者:可可西里 更新时间:2023-11-01 16:38:57 25 4
gpt4 key购买 nike

我正在使用 netty 3.3.1 开发自定义 HTTP 服务器。

我需要实现这样的东西

  1. HTTP 服务器接收请求
  2. HTTP Server 解析它并调用 HTTP 请求作为其他机器的客户端
  3. HTTP Server 等待(2)中发送的请求的响应
  4. HTTP 服务器根据在 (3) 中收到的内容发送对来自 (1) 的请求的响应

这意味着客户端请求 (2) 必须表现为同步。

我写的是基于HttpSnoopClient example但它不起作用,因为我收到了

java.lang.IllegalStateException: 
await*() in I/O thread causes a dead lock or sudden performance drop. Use addListener() instead or call await*() from a different thread.

我重构了 the code从上面提到的例子来看,现在看起来更不像这样(从 HttpSnoopClient 的第 7f 行开始):

    ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
future.addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture future) {
if (!future.isSuccess()) {
System.err.println("Cannot connect");
future.getCause().printStackTrace();
bootstrap.releaseExternalResources();
return;
}
System.err.println("Connected");

Channel channel = future.getChannel();

// Send the HTTP request.
channel.write(request);
channel.close();



// Wait for the server to close the connection.
channel.getCloseFuture().addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture future) {
System.err.println("Disconnected");
bootstrap.releaseExternalResources(); // DOES NOT WORK?
}
});
}
});

}
}

在我的 herver 处理程序的 messageReceived 函数中调用了上述示例中的 run() 命令。

所以它变成了异步的并且避免了 await* 函数。正确调用请求。但是 - 对于我来说未知的原因 - 这条线

              bootstrap.releaseExternalResources(); // DOES NOT WORK?

不起作用。它抛出一个异常,说我无法终止我当前正在使用的线程(这听起来很合理,但仍然没有给我答案如何以不同的方式做到这一点)。

我也不确定这是正确的方法吗?

也许你可以推荐一个netty中这样的事件编程技术的教程?通常如何处理一些必须按指定顺序调用并相互等待的异步请求?

谢谢,

最佳答案

如果你真的想在关闭时释放 Bootstrap ,你可以这样做:

channel.getCloseFuture().addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture future) {
System.err.println("Disconnected");
new Thread(new Runnable() {
public void run() {
bootstrap.releaseExternalResources();
}
}).start();
}
});

关于http - 如何从 netty 中的 HTTP 服务器请求处理程序正确调用 HTTP 客户端?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10063092/

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