2

My question is about creating multiple TCP clients to multiple hosts using the same event loop group in Netty 4.0.23 Final, I must admit that I don't quite understand Netty 4's client threading business, especially with the loads of confusing references to Netty 3.X.X implementations I hit through my research on the internet.

with the following code, I establish a connection with a single server, and send random commands using a command queue:

public class TCPsocket {
private static final CircularFifoQueue CommandQueue = new CircularFifoQueue(20);
private final EventLoopGroup workerGroup;
private final TcpClientInitializer tcpHandlerInit;  // all handlers shearable

public TCPsocket() {
        workerGroup = new NioEventLoopGroup();
        tcpHandlerInit = new TcpClientInitializer();

}
public void connect(String host, int port) throws InterruptedException {
    try {
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.remoteAddress(host, port);
        b.handler(tcpHandlerInit);
        Channel ch = b.connect().sync().channel();
        ChannelFuture writeCommand = null;
        for (;;) {
            if (!CommandQueue.isEmpty()) {
                writeCommand = ch.writeAndFlush(CommandExecute()); // commandExecute() fetches a command form the commandQueue and encodes it into a byte array
            }
            if (CommandQueue.isFull()) { // this will never happen ... or should never happen
                ch.closeFuture().sync();
                break;
            }
        }
        if (writeCommand != null) {
            writeCommand.sync();
        }
    } finally {
        workerGroup.shutdownGracefully();
    }
}

    public static void main(String args[]) throws InterruptedException {
        TCPsocket socket = new TCPsocket();
            socket.connect("192.168.0.1", 2101);

    }
}

in addition to executing commands off of the command queue, this client keeps receiving periodic responses from the serve as a response to an initial command that is sent as soon as the channel becomes active, in one of the registered handlers (in TCPClientInitializer implementation), I have:

@Override
public void channelActive(ChannelHandlerContext ctx) {
    ctx.writeAndFlush(firstMessage);
    System.out.println("sent first message\n");
}

which activates a feature in the connected-to server, triggering a periodic packet that is returned from the server through the life span of my application.

The problem comes when I try to use this same setup to connect to multiple servers, by looping through a string array of known server IPs:

public static void main(String args[]) throws InterruptedException {
    String[] hosts = new String[]{"192.168.0.2", "192.168.0.4", "192.168.0.5"};
    TCPsocket socket = new TCPsocket();
    for (String host : hosts) {
        socket.connect(host, 2101);
    }
}

once the first connection is established, and the server (192.168.0.2) starts sending the designated periodic packets, no other connection is attempted, which (I think) is the result of the main thread waiting on the connection to die, hence never running the second iteration of the for loop, the discussion in this question leads me to think that the connection process is started in a separate thread, allowing the main thread to continue executing, but that's not what I see here, So what is actually happening? And how would I go about implementing multiple hosts connections using the same client in Netty 4.0.23 Final?

Thanks in advance

Community
  • 1
  • 1
m_korena
  • 161
  • 1
  • 12
  • Connection does occur asynchronously on a Netty thread. You're synchronously waiting for Netty to complete the connection with b.connect().sync(). Your connect method then appears to enter an infinite loop and so the method will never return. – johnstlr Oct 23 '14 at 11:05
  • Interesting, but I am not sure how that's different from the linked-to question, which was upvoted 7 times, am I missing something? Could it be the extra break statement in the infinite loop? ... Anyways, I've shelved Netty and went with a multi-threaded nio socket channels implementation for a clearer view of the threading business, a man gotta meet his deadlines! ... but I will definitely come back to this when I have the time. – m_korena Oct 23 '14 at 11:31
  • In the linked question the loop will terminate if the user enters "bye". It will then move onto the next connection. It's not broadcasting, it's connecting to each host, running an interactive session, closing the channel when the user enters "byte" and moving onto the next host. Sorry I can't answer your question directly as I don't know the answer. I think shutting down the worker group at the end of connect is wrong because, if you do break out of the loop and try to connect to the next host, you'll have destroyed the threads Netty was using. – johnstlr Oct 23 '14 at 11:58
  • Oh ok, that makes sense, the connections are not concurrent, this does make things clear, dont worry about it, I am pass this point, implemented it in a more familiar way, was fun actually, and Netty is one less framework to worry about :-) .. Thanks for clearing my confusion about the other question, I guess I projected it onto my problem as I hoped for a shortcut copy-paste solution. – m_korena Oct 23 '14 at 12:39

0 Answers0