簡體   English   中英

如何從 HTTP 服務器請求處理程序 in.netty 正確調用 HTTP 客戶端?

[英]How to call properly HTTP client from HTTP server request handler in netty?

我正在使用 .netty 3.3.1 開發自定義 HTTP 服務器。

我需要實現這樣的東西

  1. HTTP 服務器收到請求
  2. HTTP 服務器解析它並調用 HTTP 請求作為客戶端到其他機器
  3. HTTP 服務器等待(2)中發送的請求的響應
  4. HTTP 服務器根據在 (3) 中收到的內容發送對來自 (1) 的請求的響應

這意味着客戶端請求 (2) 必須表現為同步。

我寫的是基於HttpSnoopClient 示例,但它不起作用,因為我收到

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. 

我重構了上面提到的示例中的代碼,現在它看起來不像這樣(從 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?
            }
          });   
        }
    });

  } 
}

上例中的run()命令在我的 herver 處理程序的messageReceived function 中被調用。

所以它變成了異步的並且避免了 await* 函數。 正確調用請求。 但是-出於我不知道的原因-這條線

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

不起作用。 它拋出一個異常,說我無法終止我當前正在使用的線程(這聽起來很合理,但仍然沒有給我一個如何以不同方式做到這一點的答案)。

我也不確定這是正確的方法嗎?

也許你可以在.netty 中推薦一個此類事件編程技術的教程? 通常如何處理一些必須按指定順序調用並相互等待的異步請求?

謝謝,

如果你真的想在關閉時釋放引導程序,你可以這樣做:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM