2017-06-14 42 views
0

我的服务器希望客户端在两个不同的套接字上连接,并且连接顺序非常重要。客户端必须在第一个通道ch1上连接,并且SSL握手服务器需要一段时间才能创建用户会话。在Handler中,它看起来像这样:如何在服务器建立sslConnection后在netty客户端上获得回叫

@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

回答

2

您可以从管道中检索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(); 
相关问题