use of io.netty.handler.codec.dns.DatagramDnsQueryEncoder in project netty by netty.
the class DnsClient method main.
public static void main(String[] args) throws Exception {
InetSocketAddress addr = new InetSocketAddress(DNS_SERVER_HOST, DNS_SERVER_PORT);
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group).channel(NioDatagramChannel.class).handler(new ChannelInitializer<DatagramChannel>() {
@Override
protected void initChannel(DatagramChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast(new DatagramDnsQueryEncoder()).addLast(new DatagramDnsResponseDecoder()).addLast(new SimpleChannelInboundHandler<DatagramDnsResponse>() {
@Override
protected void channelRead0(ChannelHandlerContext ctx, DatagramDnsResponse msg) {
try {
handleQueryResp(msg);
} finally {
ctx.close();
}
}
});
}
});
final Channel ch = b.bind(0).sync().channel();
DnsQuery query = new DatagramDnsQuery(null, addr, 1).setRecord(DnsSection.QUESTION, new DefaultDnsQuestion(QUERY_DOMAIN, DnsRecordType.A));
ch.writeAndFlush(query).sync();
boolean succ = ch.closeFuture().await(10, TimeUnit.SECONDS);
if (!succ) {
System.err.println("dns query timeout!");
ch.close().sync();
}
} finally {
group.shutdownGracefully();
}
}
Aggregations