2012-04-02 114 views
0

有人可以指出需要做些什麼才能重用netty中客戶端創建的套接字連接?如果我在netty的客戶端創建一個通道,多個併發線程可以使用同一個通道而不同步嗎?在netty 3.2中處理這種情況的正確方法是什麼?客戶端持久套接字

-TK

回答

1

是相同的信道,可以通過不同的主題,因爲所有的方法是線程安全的使用。

0

從不同的主題調用channel.write()沒有問題。 通過處理自定義處理程序中的事件完成讀取操作,因此不存在多線程問題。當您觸發messageReceived事件時,決定該怎麼做是您的業務。

的基本方法,以獲得通道是使用ClientBootStrap並做到這一點:

ClientBootstrap bootstrap = new ClientBootstrap(factory); 


     bootstrap.setPipelineFactory(new ChannelPipelineFactory() { 

      public ChannelPipeline getPipeline() throws Exception { 
       ChannelPipeline pipeline = Channels.pipeline(); 
       pipeline.addLast("LOGGER", new LoggingHandler("CLIENT", true)); 
       return pipeline; 
      } 
     }); 

     // Connect to the server, wait for the connection and get back the channel 
     ChannelFuture connectFuture = bootstrap.connect(new InetSocketAddress(host, port)); 

     // Wait until the connection attempt succeeds or fails. 
     Channel channel = connectFuture.awaitUninterruptibly().getChannel(); 

另一種方式可以實現這樣的處理程序和處理程序添加到管道在工廠。然後,您可以隨時訪問該頻道,但第一個解決方案似乎是實現這一訣竅的最佳方式!

public class PublicChannelHandler extends SimpleChannelUpstreamHandler { 

     Channel channel; 

     public Channel getChannel(){ 
      if (channel == null) { 
       throw new IllegalStateException("No underlying Channel is associated with this handler at the moment."); 
      } 
      return this.channel; 
     } 

     @Override 
     public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { 
      this.channel=ctx.getChannel()); 
     } 
    }