在netty客户端运行同步方法

时间:2015-07-06 20:08:46

标签: java sockets netty

我有一个netty socket客户端。从那个客户端我必须首先发送登录名和密码并等待服务器和IF的答案,只有成功,我才能继续工作。有没有办法以同步方式运行登录方法?这是我的客户代码:

Bootstrap bootstrap = new Bootstrap();
bootstrap.group(workerGroup)
    .channel(NioSocketChannel.class)
    .option(ChannelOption.SO_KEEPALIVE, true)
    .handler(new TRSClientInterfaceInitializer());

    Channel ch = bootstrap.connect(host, port).sync().channel();
    ChannelFuture lastWriteFuture = null;

    lastWriteFuture = ch.writeAndFlush("username-password" + "\n");
    ch.closeFuture().sync();

    if (lastWriteFuture != null) {
           lastWriteFuture.sync();
    }

1 个答案:

答案 0 :(得分:1)

您可以创建一个扩展SimpleChannelInboundHandler的自定义通道处理程序,您可以覆盖channelActive,您可以将身份验证信息发送到服务器。在channelRead0中,您可以验证您是否有有效的响应,并选择在auth失败时关闭通道。您的处理程序可能看起来像这样

 public class AuthHandler extends SimpleChannelInboundHandler<Object>{

  @Override
  public void channelActive(ChannelHandlerContext ctx){
     /// send your auth data to the server
  }

  @Override
  public void channelRead0(ChannelHandlerContext ctx, Object msg){
    ///verify if you received a valid auth confirm from server if not close the channel
   // you will need to invoke the fireChannelRead if its a valid post authentication data so that the messages can continue in the pipeline.
  }
 }