【问题标题】:Run synchronize method in netty client在 netty 客户端中运行同步方法
【发布时间】:2015-07-06 20:08:45
【问题描述】:

我有一个 netty 套接字客户端。从那个客户端,我必须首先发送登录名和密码,然后等待服务器和 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();
    }

【问题讨论】:

  • 你所说的成功究竟是什么意思?发送消息成功还是登录成功?

标签: java sockets netty


【解决方案1】:

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

 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.
  }
 }

【讨论】:

猜你喜欢
  • 2016-04-24
  • 1970-01-01
  • 1970-01-01
  • 2017-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
相关资源
最近更新 更多