Java 在Netty中以阻止模式检查登录
我有一个简单的netty客户端(socket)。每次向服务器发送数据时,我都必须检查客户端是否已登录。若并没有,我必须发送用户凭据并等待来自服务器的响应(true或false)。但我必须在阻塞模式下执行,若我从服务器接收到true,我可以继续发送其他数据。 我目前的代码是:Java 在Netty中以阻止模式检查登录,java,sockets,io,netty,Java,Sockets,Io,Netty,我有一个简单的netty客户端(socket)。每次向服务器发送数据时,我都必须检查客户端是否已登录。若并没有,我必须发送用户凭据并等待来自服务器的响应(true或false)。但我必须在阻塞模式下执行,若我从服务器接收到true,我可以继续发送其他数据。 我目前的代码是: EventLoopGroup workerGroup = new NioEventLoopGroup(); try { Bootstrap bootstrap = new Bootstrap(); bo
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
}
}
//从SimpleChannelInboundHandler扩展的处理程序
@凌驾
受保护的无效channelRead0(ChannelHandlerContext ctx,字符串数据)引发异常{
系统输出打印项次(数据);
System.out.flush();
如果(“成功”。等于(数据)){
isLoggedIn=true
}
}
如何在阻塞模式下实现此逻辑?我在网上找不到任何解决办法。有什么帮助吗?请在写入操作完成之前阻止客户端:
lastWriteFuture = ch.writeAndFlush(message.getDataString);
lastWriteFuture.await();
您的服务器可能会写入一些响应以指示请求是否成功:
//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!");
}
//从SimpleChannelInboundHandler扩展的处理程序
@凌驾
受保护的无效channelRead0(ChannelHandlerContext ctx,字符串数据)引发异常{
系统输出打印项次(数据);
System.out.flush();
如果(“成功”。等于(数据)){
isLoggedIn=true
ctx.channel().writeAndFlush(“成功!”);
返回;
}
ctx.channel().writeAndFlush(“失败!”);
}
在TRSClientInterfaceInitializer处理程序中处理服务器的响应 我必须把它写在最后一刻;lastWriteFuture=ch.writeAndFlush(message.getDataString)之后;或在lastWriteFuture=ch.writeAndFlush(“登录密码”)之后;简单而伟大的解决方案。tnx。