【发布时间】:2023-08-23 15:51:01
【问题描述】:
我正在尝试使用the following code,它是 Netty Nio 中 Web 套接字的一种实现。我已经实现了一个 JavaFx Gui,我想从 Gui 中读取从服务器或其他客户端接收到的消息。 NettyClient 代码如下:
public static ChannelFuture 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(i -> {
synchronized (lock) {
connectedClients = i;
lock.notifyAll();
}
}));
}
});
ChannelFuture f = b.connect(host, port).sync();
//f.channel().closeFuture().sync();
return f;
}
finally {
//workerGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
ChannelFuture ret;
ClientHandler obj = new ClientHandler(i -> {
synchronized (lock) {
connectedClients = i;
lock.notifyAll();
}
});
ret = callBack();
int connected = connectedClients;
if (connected != 2) {
System.out.println("The number if the connected clients is not two before locking");
synchronized (lock) {
while (true) {
connected = connectedClients;
if (connected == 2)
break;
System.out.println("The number if the connected clients is not two");
lock.wait();
}
}
}
System.out.println("The number if the connected clients is two: " + connected );
ret.channel().read(); // can I use that from other parts of the code in order to read the incoming messages?
}
如何使用从我的代码的其他部分的回调返回的 channelFuture 来读取传入的消息?是否需要再次调用callBack,或者如何才能收到频道的更新消息?我可以从我的代码(在按钮事件中)使用ret.channel().read() 之类的东西(以便获取最后一条消息)吗?
【问题讨论】:
-
你能用这样的东西吗:*.com/questions/34977477/… ?
-
检查答案。不确定我是否理解答案中提到的远程服务器。
-
其实我不能使用私有 final SynchronousQueue
> 队列;在 clientHandler 内部。
标签: java sockets web netty nio