Netty - 频道立即关闭
问题描述:
我已经开始使用netty,并且(显然)想要在客户端和服务器之间发送消息。由于我处于早期阶段,所以我对简单的东西有问题,在这种情况下,它会发送一条消息。这是我创造我的服务器和我的客户:Netty - 频道立即关闭
客户:
public void run() throws Exception
{
EventLoopGroup group = new NioEventLoopGroup();
try
{
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioSocketChannel.class)
.handler(new SecureChatClientInitializer());
b.option(ChannelOption.SO_KEEPALIVE, true);
// Start the connection attempt.
ChannelFuture future = b.connect(new InetSocketAddress(host, port));
Channel ch = future.awaitUninterruptibly().channel();
ch.writeAndFlush("hi\r\n");
// Wait until all messages are flushed before closing the channel.
if (lastWriteFuture != null)
{
lastWriteFuture.sync();
}
} finally
{
// The connection is closed automatically on shutdown.
group.shutdownGracefully();
}
}
服务器:
public void run() throws InterruptedException
{
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try
{
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new SecureChatServerInitializer(sessionManager));
b.option(ChannelOption.SO_KEEPALIVE, true);
b.bind(port).sync().channel().closeFuture().sync();
} finally
{
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
客户初始化程序:
public class SecureChatClientInitializer extends ChannelInitializer<SocketChannel>
{
@Override
public void initChannel(SocketChannel ch) throws Exception
{
ChannelPipeline pipeline = ch.pipeline();
SSLEngine engine =
SecureChatSslContextFactory.getClientContext().createSSLEngine();
engine.setUseClientMode(true);
pipeline.addLast("ssl", new SslHandler(engine));
pipeline.addLast("framer", new DelimiterBasedFrameDecoder(
8192, Delimiters.lineDelimiter()));
pipeline.addLast("decoder", new StringDecoder());
pipeline.addLast("encoder", new StringEncoder());
pipeline.addLast("handler", new SecureChatClientHandler());
}
}
服务器初始化程序:
public class SecureChatServerInitializer extends ChannelInitializer<SocketChannel>
{
...
@Override
public void initChannel(SocketChannel ch) throws Exception
{
ChannelPipeline pipeline = ch.pipeline();
SSLEngine engine =
SecureChatSslContextFactory.getServerContext().createSSLEngine();
engine.setUseClientMode(false);
pipeline.addLast("ssl", new SslHandler(engine));
pipeline.addLast("framer", new DelimiterBasedFrameDecoder(
8192, Delimiters.lineDelimiter()));
pipeline.addLast("decoder", new StringDecoder());
pipeline.addLast("encoder", new StringEncoder());
pipeline.addLast("handler", new SecureChatServerHandler(sessionManager));
}
}
正如您可能已经从查看源代码中猜到的一样:是的,其中的一部分来自SecureChatExample。我编辑了部分内容,不明白为什么它不再工作。当执行客户端,我只得到错误信息的一行:
java.nio.channels.ClosedChannelException
答
只有打电话group.shutdownGracefully();
当你真正想退出客户端。如果您从客户端删除该行,则Channel
将保持打开状态。
此外,您只需在发送的所有邮件末尾加上\n
后缀。
答
除此之外,你可以关闭该通道是这样的:
@Override
public void channelActive(ChannelHandlerContext ctx) {
ctx.channel().pipeline().remove(this);
}
这做到了!谢谢! :d – user1406177