2012-04-02 3 views
0

netty에서 클라이언트가 만든 소켓 연결을 다시 사용하려면 수행해야 할 작업을 누군가가 알려줄 수 있습니까? Netty에서 클라이언트 측의 채널을 만들면 여러 동시 스레드가 동기화없이 동일한 채널을 사용할 수 있습니까? netty 3.2에서이 시나리오를 처리하는 올바른 방법은 무엇입니까? 모든 메소드는 스레드 안전으로클라이언트 영구 소켓

- TK

답변

1

예 동일 채널은 다른 스레드에서 사용할 수 있습니다.

0

다른 스레드에서 channel.write()를 호출해도 아무런 문제가 없습니다. 멀티 스레딩 문제가 없도록 사용자 지정 처리기의 이벤트를 처리하여 읽기가 완료됩니다. messageReceived 이벤트가 발생할 때 수행 할 작업을 결정하는 것은 귀하의 비즈니스입니다.

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(); 

또 다른 방법은 같은 핸들러를 구현하고 공장에서 파이프 라인에 처리기를 추가 할 수 있습니다 :

채널을 얻을 수있는 기본적인 방법은 ClientBootStrap를 사용하고 그렇게하는 것입니다. 그런 다음 언제든지 채널에 액세스 할 수 있지만 첫 번째 솔루션이 트릭을 수행하는 가장 좋은 방법 인 것처럼 보입니다!

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()); 
     } 
    }