Netty 4.0.23多主机单客户端

时间:2014-10-22 10:03:43

标签: java multithreading sockets connection netty

我的问题是在Netty 4.0.23中使用相同的事件循环组为多个主机创建多个TCP客户端。最后,我必须承认我不太了解Netty 4的客户端线程业务,尤其是随着我对Netty 3.XX实施的混乱引用,我在互联网上进行了研究。

使用以下代码,我与单个服务器建立连接,并使用命令队列发送随机命令:

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);

    }
}

除了执行命令队列之外的命令之外,该客户端还在一个注册的处理程序中(TCPClientInitializer中)继续接收来自服务器的定期响应,作为对通道激活后立即发送的初始命令的响应。实施),我有:

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

激活连接服务器中的某个功能,触发在我的应用程序的生命周期内从服务器返回的定期数据包。

当我尝试使用相同的设置连接到多个服务器时出现问题, 通过循环遍历已知服务器IP的字符串数组:

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);
    }
}

一旦建立了第一个连接,并且服务器(192.168.0.2)开始发送指定的周期性数据包,则不会尝试其他连接,这(我认为)是主线程等待连接死亡的结果,因此永远不会运行for循环的第二次迭代,this question中的讨论让我认为连接过程是在一个单独的线程中启动的,允许主线程继续执行,但那不是什么我在这里看到,那么实际发生了什么?我将如何在Netty 4.0.23 Final中使用相同的客户端实现多个主机连接?

提前致谢

0 个答案:

没有答案