1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.handler.address;
17
18 import io.netty.channel.ChannelHandler.Sharable;
19 import io.netty.channel.ChannelHandlerContext;
20 import io.netty.channel.ChannelOutboundHandlerAdapter;
21 import io.netty.channel.ChannelPromise;
22 import io.netty.resolver.AddressResolver;
23 import io.netty.resolver.AddressResolverGroup;
24 import io.netty.util.concurrent.Future;
25 import io.netty.util.concurrent.FutureListener;
26 import io.netty.util.internal.ObjectUtil;
27
28 import java.net.SocketAddress;
29
30
31
32
33
34
35 @Sharable
36 public class ResolveAddressHandler extends ChannelOutboundHandlerAdapter {
37
38 private final AddressResolverGroup<? extends SocketAddress> resolverGroup;
39
40 public ResolveAddressHandler(AddressResolverGroup<? extends SocketAddress> resolverGroup) {
41 this.resolverGroup = ObjectUtil.checkNotNull(resolverGroup, "resolverGroup");
42 }
43
44 @Override
45 public void connect(final ChannelHandlerContext ctx, SocketAddress remoteAddress,
46 final SocketAddress localAddress, final ChannelPromise promise) {
47 AddressResolver<? extends SocketAddress> resolver = resolverGroup.getResolver(ctx.executor());
48 if (resolver.isSupported(remoteAddress) && !resolver.isResolved(remoteAddress)) {
49 resolver.resolve(remoteAddress).addListener(new FutureListener<SocketAddress>() {
50 @Override
51 public void operationComplete(Future<SocketAddress> future) {
52 Throwable cause = future.cause();
53 if (cause != null) {
54 promise.setFailure(cause);
55 } else {
56 ctx.connect(future.getNow(), localAddress, promise);
57 }
58 ctx.pipeline().remove(ResolveAddressHandler.this);
59 }
60 });
61 } else {
62 ctx.connect(remoteAddress, localAddress, promise);
63 ctx.pipeline().remove(this);
64 }
65 }
66 }