如何使客户端连接到netty 4中具有相同客户端引导程序的多个主机?

时间:2017-03-02 19:23:21

标签: java network-programming netty

在此代码中当客户端连接到新服务器时,先前与服务器连接的通道将变为非活动状态,并且该通道将分配给新连接的服务器。我想要一种存储所有通道的方法,这可以通过为每个连接的服务器分配一个单独的通道来完成。

EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
    Bootstrap client = new Bootstrap();
    client.group(workerGroup);
    client.channel(NioSocketChannel.class);
    client.handler(new ChannelInitializer<SocketChannel>() {
    @Override
     public void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new ObjectEncoder(),new ObjectDecoder(ClassResolvers.weakCachingResolver(Message.class.getClassLoader())),new ClientHandler());
            }
     });
     Thread.sleep(10000);

     ChannelFuture future = client.connect("localhost", destination_Port).sync();
     if(future.isSuccess()) {
         System.out.println("Connected to node " +destination_Node + " port is "+ destination_Port);
         // Storing the channel in the map to reuse later
         channelMap.put(destination_Node,future);
     }
     // data is an object which will be sent to the server 
     data.setSender(nodeID);
     data.setClockTime(clockTime);
     future.channel().writeAndFlush(data);
}
finally {
     workerGroup.shutdownGracefully();
}

从我经历的消息来源我了解到,在ChannelFactory的帮助下,我将能够为每个连接的主机提供单独的通道,但我无法实现它可以有人帮我这个吗?

0 个答案:

没有答案