mercredi 29 novembre 2017

Netty Nio read the upcoming messages from ChannelFuture in Java

I am trying to use the following code which is an implementation of web sockets in Netty Nio. I have implment a JavaFx Gui and from the Gui I want to read the messages that are received from the Server or from other clients. The NettyClient code is like the following:

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?
}

How can I use the returned channelFuture from the callBack from other parts of my code in order to read the incoming messages? Is it possible to call callBack just once? And then from my code to do something like ret.channel().read()?




Aucun commentaire:

Enregistrer un commentaire