我已经开始使用 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