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