在同一个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进行了测试,我无法弄清楚我做错了什么。
为什么客户端在服务器关闭后仍然可以向服务器发送数据?
答案 0 :(得分:0)
客户端可以发送数据,但clientChannel.write(..)的ChannelFuture应该失败。
您可以查看:
boolean success = clientChannel.write(new byte[] { 1, 2, 3 }).awaitUninteruptable().isSucess();
或者使用ChannelFutureListener以异步方式进行通知。