[英]Netty Nio read the upcoming messages from ChannelFuture in Java
我试图使用以下代码 ,这是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?
}
如何从我的代码的其他部分使用callBack中返回的channelFuture来读取传入的消息? 我是否需要再次呼叫callBack,或者我如何才能收到频道的更新消息? 我可以使用我的代码(在一个按钮事件中)像ret.channel().read()
(以便采取最后一条消息)?
通过读取该代码,NettyClient用于创建连接(ClientHandler),一旦连接完成,Netty调用ClientHandler.channelActive,如果要将数据发送到服务器,则应在此处添加一些代码。 如果此连接从表单服务器获取消息,则由Netty调用ClientHandler.channelRead,将您的代码置于处理消息中。
您还需要阅读doc以了解netty编码器/解码器的工作原理。
如何从我的代码的其他部分使用callBack中返回的channelFuture来读取传入的消息?
分享NettyClient创建的ClientHandler(NettyClient.java第29行)
我是否需要再次呼叫callBack,或者我如何才能收到频道的更新消息?
如果服务器消息到来,则调用ClientHandler.channelRead。
我可以使用我的代码(在一个按钮事件中)像ret.channel()。read()(以便采取最后一条消息)?
是的,你可以,但不是一个网络方式,与netty玩,你写回调(当消息来,当消息发送...),等netty调用你的代码,即:驱动程序是netty,而不是你。
最后,你真的需要这么重的库来做网络吗?如果没有,试试这个代码 ,它简单易懂
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.