2012-05-07 72 views
1

在同一個jvm中運行Netty客戶端和服務器並嘗試停止服務器時出現問題。這裏是我的代碼來舉例說明這一點:Netty服務器在本地運行時無法正常關機

@BeforeMethod 
public void setUp() { 
    serverBootstrap = new ServerBootstrap(new DefaultLocalServerChannelFactory()); 
    serverBootstrap.getPipeline().addLast("my-server-handler", new ServerHandler()); 
    LocalAddress local = new LocalAddress("1"); 
    serverChannel = serverBootstrap.bind(local); 

    clientBootstrap = new ClientBootstrap(new DefaultLocalClientChannelFactory()); 

    clientBootstrap.setPipelineFactory(new ChannelPipelineFactory() { 
     @Override 
     public ChannelPipeline getPipeline() throws Exception { 
      ChannelPipeline pipeline = Channels.pipeline(); 
      pipeline.addLast("my-client-handler", new ClientHandler()); 
      return pipeline; 
     } 
    }); 

    ChannelFuture future = clientBootstrap.connect(local); 
    if (future.isSuccess()) 
     System.out.println("Client connected"); 
    clientChannel = future.getChannel(); 
} 

@AfterMethod 
public void tearDown() { 
    closeServer(); 
    clientChannel.close().awaitUninterruptibly(); 
    clientBootstrap.releaseExternalResources(); 
} 

@Test 
public void shoulClose() {   
    sendData(); 
    closeServer(); 
    sendData();  
} 

private void closeServer() { 
    serverChannel.close().awaitUninterruptibly(); 
    serverBootstrap.releaseExternalResources(); 
} 

private void sendData() { 
    clientChannel.write(new byte[] { 1, 2, 3 }); 
} 

我與Netty的3.4.0.Final和3.4.4.Final測試這一點,我想不出什麼我做錯了。

爲什麼客戶端在服務器關閉後仍然可以向服務器發送數據?

回答

0

客戶端可以發送數據,但clientChannel.write(..)的ChannelFuture應該失敗。

你可以檢查一下:

boolean success = clientChannel.write(new byte[] { 1, 2, 3 }).awaitUninteruptable().isSucess(); 

或者使用ChannelFutureListener以異步方式得到notifed。

相關問題