【发布时间】:2018-04-11 11:03:41
【问题描述】:
我有一个交换信息的服务器和客户端架构。我想从服务器返回连接通道的数量。我想使用 promise 将服务器的消息返回给客户端。我的代码是:
public static void callBack () throws Exception{
String host = "localhost";
int port = 8080;
try {
Bootstrap b = new Bootstrap();
b.group(workerGroup);
b.channel(NioSocketChannel.class);
b.option(ChannelOption.SO_KEEPALIVE, true);
b.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new RequestDataEncoder(), new ResponseDataDecoder(), new ClientHandler(promise));
}
});
ChannelFuture f = b.connect(host, port).sync();
//f.channel().closeFuture().sync();
}
finally {
//workerGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
callBack();
while (true) {
Object msg = promise.get();
System.out.println("The number if the connected clients is not two");
int ret = Integer.parseInt(msg.toString());
if (ret == 2){
break;
}
}
System.out.println("The number if the connected clients is two");
}
当我运行一个客户端时,它总是收到消息The number if the connected clients is not two,并且返回的数字总是一。当我运行第二个客户端时,它总是接收一个返回值,但是,第一个客户端仍然接收一个。对于第一个客户的情况,我找不到更新承诺的正确方法。
编辑: 客户端服务器:
public class ClientHandler extends ChannelInboundHandlerAdapter {
public final Promise<Object> promise;
public ClientHandler(Promise<Object> promise) {
this.promise = promise;
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
RequestData msg = new RequestData();
msg.setIntValue(123);
msg.setStringValue("all work and no play makes jack a dull boy");
ctx.writeAndFlush(msg);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println(msg);
promise.trySuccess(msg);
}
}
来自客户端处理程序的代码,用于存储从服务器接收到的消息到 Promise。
【问题讨论】:
-
当你说promise时,你的意思是非阻塞吗?
-
我的意思是这个Object msg = promise.get();,这个值有服务器的retuned消息。
-
你可以关注我对不同问题的回答stackoverflow.com/questions/46852221/…
-
@konstantin 根据您的问题,您的意思是:
promise.get()返回连接到您服务器的客户端(通道)数量?? -
在客户端处理程序中存储我从客户端读取的消息。 github.com/kristosh/netty-nio-Client-Server
标签: java sockets web netty nio