2013-01-16 22 views
0

我想了Netty(版本3.6.1.final)整合到我們現有的系統外訪問的Netty處理方法,所以我可以代替目前的NIO代碼。如何從正常流動

目前我們有一個消息總線,事件排隊等待其他聽衆來處理,並把另一個事件背部總線上進行進一步的處理。

在我Netty的業務邏輯處理程序的的messageReceived()方法,我將增加的輸入請求到總線。我將要傳遞的一件事是來自Netty事件消息的數據。

我的數字,我應該通過ChannelHandlerContext在此InputEvent的與接收到的數據/消息一起。所以,最終當處理OutputEvent,它可以使用最初傳遞給周圍的處理後的數據發送回請求的客戶機上的正確Netty的海峽ChannelHandlerContext。

那麼如何才能正在處理OutputEvent綁回了Netty輸出任務?

難道我用我已經使用作爲輸入,處理後的數據ChannelHandlerContext發出一些呼喚。我不想捆綁輸出任務。從Netty的處理器

代碼段。

public void messageReceived(
     ChannelHandlerContext ctx, MessageEvent e) { 

    byte[] message = (byte[])e.getMessage(); 

    try { 
      data.add(message); 
     } 
    catch(IOException ioe) 
     { 
      logger.error(ioe); 
     } 

    InputEvent ie = new InputEvent(ctx, this, data.getBuffer()); 

    try { 
       bus.enqueue(ie); 
    } 
    catch(Exception ex) 
    { 
     logger.error(ex); 
    } 

來自輸出處理器的代碼片段。

public void run() { 


    // note that the OutputEvent (event) is available here. This is not a Netty event. 
    ChannelHandlerContext ctx = event.getHandlerContext(); 
    ClientChannel handler = event.getHandler(); 

    // I need to send the data in event.getBuffer() back. 

// Now what do I do here??? 


… 
… 
… 

} 

謝謝。

回答

1

你只是會打電話:

InputEvent event = ... 
ChannelHandlerContext ctx = .... 
ctx.write(event.getBuffer()); 

或者:

InputEvent event = ... 
Channel channel = .... 
channel.write(event.getBuffer()); 
+0

就這麼簡單。大! Netty將極大地幫助我們處理我們的NIO問題。謝謝諾曼。 – MLightheart

+0

我想問這個。當我寫出來的數據到CTX或通道,將基本上它交給渠道,我不會在輸出任務等待寫週期才能完成?通過寫週期,我的意思是讓數據到達客戶端。謝謝。 – MLightheart

+0

是的,它不會等待...如果你需要等待,你可以在返回的ChannelFuture調用的await *(),但在IO線程不這樣做.. –

0
// Make a new connection. 
    ChannelFuture connectFuture = 
     bootstrap.connect(new InetSocketAddress(host, port)); 

    // Wait until the connection is made successfully. 
    Channel channel = connectFuture.awaitUninterruptibly().getChannel(); 

    // Get the handler instance to retrieve the answer. 
    FactorialClientHandler handler = 
     (FactorialClientHandler) channel.getPipeline().getLast();//get("your handler name")