本文介绍了在Netty中以阻止模式检查登录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的netty客户端(套接字)。每当我向服务器发送数据时,我必须检查客户端是否已登录。如果没有,我必须发送用户凭据并等待服务器的响应为true或false。但我必须在阻止模式下执行此操作,如果我从服务器收到true,我可以继续发送其他数据。
我当前的代码是:

I have a simple netty client (socket). every time when I send data to server, I must check is client is logged in or not. If not, I must send user credentials and wait response from server with true or false. but I must do it in blocking mode and if I receive true from server, I can continue sending other data. my current code is:

EventLoopGroup workerGroup = new NioEventLoopGroup();   
try {
    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;

    for (Message message : list) {
        if (!isLoggedIn) {
            lastWriteFuture = ch.writeAndFlush("loginpassword");
        }
        //if login is success, I must loop through all data in list and send other data to server
        lastWriteFuture = ch.writeAndFlush(message.getDataString);
    }

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

这是我的处理程序:

//handler extended from SimpleChannelInboundHandler<String>
@Override
protected void channelRead0(ChannelHandlerContext ctx, String data) throws Exception {
    System.out.println(data);
    System.out.flush();
    if ("success".equals(data)) {
        isLoggedIn = true
    }
}

如何在阻塞模式下实现此逻辑?我在网上找不到任何解决方案。有帮助吗?请

How I can implement this logic in blocking mode? I can't find any solution in web. Any help? Pls.

推荐答案

阻止客户端直到写入操作完成:

blocking client until write operation finish:

lastWriteFuture = ch.writeAndFlush(message.getDataString);
lastWriteFuture.await();

您的服务器可能会写一些回复来表明请求是否成功:

your server may write some response to indicate whether the request is successful:

//handler extended from SimpleChannelInboundHandler<String>
@Override
protected void channelRead0(ChannelHandlerContext ctx, String data) throws  Exception {
  System.out.println(data);
  System.out.flush();
  if ("success".equals(data)) {
    isLoggedIn = true
    ctx.channel().writeAndFlush("success!");
    return;
  }
  ctx.channel().writeAndFlush("fail!");
}

TRSClientInterfaceInitializer 处理程序中处理服务器的响应。

handle server's response in your TRSClientInterfaceInitializer handler.

这篇关于在Netty中以阻止模式检查登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 15:58