在此代码中当客户端连接到新服务器时,先前与服务器连接的通道将变为非活动状态,并且该通道将分配给新连接的服务器。我想要一种存储所有通道的方法,这可以通过为每个连接的服务器分配一个单独的通道来完成。
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的帮助下,我将能够为每个连接的主机提供单独的通道,但我无法实现它可以有人帮我这个吗?