【问题标题】:Netty server not shutdown correctly when running locallyNetty 服务器在本地运行时无法正确关闭
【发布时间】:2012-05-08 16:13:32
【问题描述】:

在同一 jvm 中运行 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 对此进行了测试,但我不知道我做错了什么。

为什么服务器宕机后客户端还能向服务器发送数据?

【问题讨论】:

    标签: netty


    【解决方案1】:

    客户端可以发送数据,但是 clientChannel.write(..) 的 ChannelFuture 应该失败。

    您可以通过以下方式进行检查:

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

    或者使用 ChannelFutureListener 以异步方式获得通知。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-22
      • 1970-01-01
      • 1970-01-01
      • 2021-08-25
      • 2012-02-17
      • 1970-01-01
      相关资源
      最近更新 更多