Checking entry into lock mode in Netty
I have a simple netty client (socket). every time i post data to the server i have to check if the client is logged in or not. If not, I have to send the user credentials and wait for a response from the server with true or false. but i have to do it in blocking mode and if i get true from server i can continue sending other data. my current code:
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 ////
this is my handler:
//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 can I implement this logic in blocking mode? I cannot find a solution on the internet. Any help? Pls.
+3
source to share
1 answer
blocking the client until the write operation completes:
lastWriteFuture = ch.writeAndFlush(message.getDataString); lastWriteFuture.await();
your server may write some response to indicate if 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!");
}
edit the server response in your TRSClientInterfaceInitializer handler .
+3
source to share