Netty Nio在Java中阅读来自ChannelFuture的即将发布的消息

时间:2017-11-29 14:53:07

标签: java sockets web netty nio

我正在尝试使用the following code,它是Netty Nio中Web套接字的一种实现。我有一个JavaFx Gui和Gui,我想读取从服务器或其他客户端收到的消息。 NettyClient代码如下所示:

class NewsFeedSerializer(serializers.ModelSerializer):
    """Serializer to map the Model instance into JSON format."""

    def to_representation(self, instance):
        data = super(NewsFeedSerializer, self).to_representation(instance)
        """Modify your response data here"""
        return dict(feeds=data)

如何从我的代码的其他部分使用callBack中返回的channelFuture来读取传入的消息?我是否需要再次呼叫callBack,或者我如何才能收到频道的更新消息?我可以使用我的代码(在按钮事件中)使用类似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? } 的内容(以便获取最后一条消息)吗?

1 个答案:

答案 0 :(得分:0)

通过读取该代码,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,而不是你

最后,你真的需要这么重的网络来做网络吗?如果没有,试试This code,简单易懂