我的服务器希望客户端连接到两个不同的套接字上,连接顺序很重要。客户端必须在第一个通道ch1
连接,并在 SSL 握手服务器需要一些时间创建用户会话之后进行连接。在处理程序中,它看起来像这样:
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
log.debug("channelRegistered);
ctx.pipeline().get(SslHandler.class).handshakeFuture().addListener(
future -> initSession(ctx));
}
InitSession 方法创建内部对象来跟踪客户端。只有在 initSession 完成后,服务器才期望从此客户端在第二个通道ch2
上进行连接。
我坚持编写客户端代码来执行此连接顺序。 天真的方式很简单:
public static void main(String[] args) throws Exception {
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
SslContext sslContext = provideSslContext();
Bootstrap b = new Bootstrap();
b.group(workerGroup)
.channel(NioSocketChannel.class)
.handler(new Channelinitializer(sslContext));
Channel ch1 = b.connect("localhost", 8008).sync().channel();
Thread.sleep(1000);
Bootstrap b1 = new Bootstrap();
b1.group(workerGroup)
.channel(NioSocketChannel.class)
.handler(new Channelinitializer(sslContext));
Channel ch2 = b1.connect("localhost", 8009).sync().channel();
}finally {
workerGroup.shutdownGracefully();
}
}
连接ch1
后,我们只需等待一段时间,以确保服务器执行所有必需的操作。 解决方案应该有多强大?是否有任何回调可用于触发ch2
连接?我正在使用netty 4.0.36.Final
只需从管道中检索SslHandler
,然后等待handshakeFuture
或向其添加侦听器。然后在完成后进行第二次连接。
像这样:
SslContext sslContext = provideSslContext();
Bootstrap b = new Bootstrap();
b.group(workerGroup)
.channel(NioSocketChannel.class)
.handler(new Channelinitializer(sslContext));
Channel ch1 = b.connect("localhost", 8008).sync().channel();
ch1.pipeline.get(SslHandler.class).handshakeFuture().sync()
Bootstrap b1 = new Bootstrap();
b1.group(workerGroup)
.channel(NioSocketChannel.class)
.handler(new Channelinitializer(sslContext));
Channel ch2 = b1.connect("localhost", 8009).sync().channel();