2012-05-07 75 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。

相关问题