Search in sources :

Example 61 with DatagramPacket

use of io.netty.channel.socket.DatagramPacket in project netty by netty.

the class DatagramPacketEncoder method encode.

@Override
protected void encode(ChannelHandlerContext ctx, AddressedEnvelope<M, InetSocketAddress> msg, List<Object> out) throws Exception {
    assert out.isEmpty();
    encoder.encode(ctx, msg.content(), out);
    if (out.size() != 1) {
        throw new EncoderException(StringUtil.simpleClassName(encoder) + " must produce only one message.");
    }
    Object content = out.get(0);
    if (content instanceof ByteBuf) {
        // Replace the ByteBuf with a DatagramPacket.
        out.set(0, new DatagramPacket((ByteBuf) content, msg.recipient(), msg.sender()));
    } else {
        throw new EncoderException(StringUtil.simpleClassName(encoder) + " must produce only ByteBuf.");
    }
}
Also used : DatagramPacket(io.netty.channel.socket.DatagramPacket) ByteBuf(io.netty.buffer.ByteBuf)

Example 62 with DatagramPacket

use of io.netty.channel.socket.DatagramPacket in project netty by netty.

the class QuoteOfTheMomentClient method main.

public static void main(String[] args) throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true).handler(new QuoteOfTheMomentClientHandler());
        Channel ch = b.bind(0).sync().channel();
        // Broadcast the QOTM request to port 8080.
        ch.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer("QOTM?", CharsetUtil.UTF_8), SocketUtils.socketAddress("255.255.255.255", PORT))).sync();
        // print an error message and quit.
        if (!ch.closeFuture().await(5000)) {
            System.err.println("QOTM request timed out.");
        }
    } finally {
        group.shutdownGracefully();
    }
}
Also used : EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Channel(io.netty.channel.Channel) NioDatagramChannel(io.netty.channel.socket.nio.NioDatagramChannel) DatagramPacket(io.netty.channel.socket.DatagramPacket) Bootstrap(io.netty.bootstrap.Bootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 63 with DatagramPacket

use of io.netty.channel.socket.DatagramPacket in project netty by netty.

the class DnsNameResolverTest method testTruncated0.

private static void testTruncated0(boolean tcpFallback, final boolean truncatedBecauseOfMtu) throws IOException {
    final String host = "somehost.netty.io";
    final String txt = "this is a txt record";
    final AtomicReference<DnsMessage> messageRef = new AtomicReference<DnsMessage>();
    TestDnsServer dnsServer2 = new TestDnsServer(new RecordStore() {

        @Override
        public Set<ResourceRecord> getRecords(QuestionRecord question) {
            String name = question.getDomainName();
            if (name.equals(host)) {
                return Collections.<ResourceRecord>singleton(new TestDnsServer.TestResourceRecord(name, RecordType.TXT, Collections.<String, Object>singletonMap(DnsAttribute.CHARACTER_STRING.toLowerCase(), txt)));
            }
            return null;
        }
    }) {

        @Override
        protected DnsMessage filterMessage(DnsMessage message) {
            // Store a original message so we can replay it later on.
            messageRef.set(message);
            if (!truncatedBecauseOfMtu) {
                // Create a copy of the message but set the truncated flag.
                DnsMessageModifier modifier = modifierFrom(message);
                modifier.setTruncated(true);
                return modifier.getDnsMessage();
            }
            return message;
        }
    };
    dnsServer2.start();
    DnsNameResolver resolver = null;
    ServerSocket serverSocket = null;
    try {
        DnsNameResolverBuilder builder = newResolver().queryTimeoutMillis(10000).resolvedAddressTypes(ResolvedAddressTypes.IPV4_PREFERRED).maxQueriesPerResolve(16).nameServerProvider(new SingletonDnsServerAddressStreamProvider(dnsServer2.localAddress()));
        if (tcpFallback) {
            // If we are configured to use TCP as a fallback also bind a TCP socket
            serverSocket = new ServerSocket();
            serverSocket.setReuseAddress(true);
            serverSocket.bind(new InetSocketAddress(dnsServer2.localAddress().getPort()));
            builder.socketChannelType(NioSocketChannel.class);
        }
        resolver = builder.build();
        if (truncatedBecauseOfMtu) {
            resolver.ch.pipeline().addFirst(new ChannelInboundHandlerAdapter() {

                @Override
                public void channelRead(ChannelHandlerContext ctx, Object msg) {
                    if (msg instanceof DatagramPacket) {
                        // Truncate the packet by 1 byte.
                        DatagramPacket packet = (DatagramPacket) msg;
                        packet.content().writerIndex(packet.content().writerIndex() - 1);
                    }
                    ctx.fireChannelRead(msg);
                }
            });
        }
        Future<AddressedEnvelope<DnsResponse, InetSocketAddress>> envelopeFuture = resolver.query(new DefaultDnsQuestion(host, DnsRecordType.TXT));
        if (tcpFallback) {
            // If we are configured to use TCP as a fallback lets replay the dns message over TCP
            Socket socket = serverSocket.accept();
            InputStream in = socket.getInputStream();
            // skip length field
            assertTrue((in.read() << 8 | (in.read() & 0xff)) > 2);
            int txnId = in.read() << 8 | (in.read() & 0xff);
            IoBuffer ioBuffer = IoBuffer.allocate(1024);
            // Must replace the transactionId with the one from the TCP request
            DnsMessageModifier modifier = modifierFrom(messageRef.get());
            modifier.setTransactionId(txnId);
            new DnsMessageEncoder().encode(ioBuffer, modifier.getDnsMessage());
            ioBuffer.flip();
            ByteBuffer lenBuffer = ByteBuffer.allocate(2);
            lenBuffer.putShort((short) ioBuffer.remaining());
            lenBuffer.flip();
            while (lenBuffer.hasRemaining()) {
                socket.getOutputStream().write(lenBuffer.get());
            }
            while (ioBuffer.hasRemaining()) {
                socket.getOutputStream().write(ioBuffer.get());
            }
            socket.getOutputStream().flush();
            // Let's wait until we received the envelope before closing the socket.
            envelopeFuture.syncUninterruptibly();
            socket.close();
            serverSocket.close();
        }
        AddressedEnvelope<DnsResponse, InetSocketAddress> envelope = envelopeFuture.syncUninterruptibly().getNow();
        assertNotNull(envelope.sender());
        DnsResponse response = envelope.content();
        assertNotNull(response);
        assertEquals(DnsResponseCode.NOERROR, response.code());
        int count = response.count(DnsSection.ANSWER);
        assertEquals(1, count);
        List<String> texts = decodeTxt(response.recordAt(DnsSection.ANSWER, 0));
        assertEquals(1, texts.size());
        assertEquals(txt, texts.get(0));
        if (tcpFallback) {
            assertFalse(envelope.content().isTruncated());
        } else {
            assertTrue(envelope.content().isTruncated());
        }
        assertTrue(envelope.release());
    } finally {
        dnsServer2.stop();
        if (resolver != null) {
            resolver.close();
        }
    }
}
Also used : QuestionRecord(org.apache.directory.server.dns.messages.QuestionRecord) Set(java.util.Set) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet) InetSocketAddress(java.net.InetSocketAddress) DnsMessage(org.apache.directory.server.dns.messages.DnsMessage) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) DnsMessageEncoder(org.apache.directory.server.dns.io.encoder.DnsMessageEncoder) DatagramPacket(io.netty.channel.socket.DatagramPacket) DefaultDnsQuestion(io.netty.handler.codec.dns.DefaultDnsQuestion) AddressedEnvelope(io.netty.channel.AddressedEnvelope) InputStream(java.io.InputStream) AtomicReference(java.util.concurrent.atomic.AtomicReference) ServerSocket(java.net.ServerSocket) ByteBuffer(java.nio.ByteBuffer) IoBuffer(org.apache.mina.core.buffer.IoBuffer) RecordStore(org.apache.directory.server.dns.store.RecordStore) DnsResponse(io.netty.handler.codec.dns.DnsResponse) DnsMessageModifier(org.apache.directory.server.dns.messages.DnsMessageModifier) ServerSocket(java.net.ServerSocket) DatagramSocket(java.net.DatagramSocket) Socket(java.net.Socket) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 64 with DatagramPacket

use of io.netty.channel.socket.DatagramPacket in project netty by netty.

the class DatagramDnsQueryEncoder method encode.

@Override
protected void encode(ChannelHandlerContext ctx, AddressedEnvelope<DnsQuery, InetSocketAddress> in, List<Object> out) throws Exception {
    final InetSocketAddress recipient = in.recipient();
    final DnsQuery query = in.content();
    final ByteBuf buf = allocateBuffer(ctx, in);
    boolean success = false;
    try {
        encoder.encode(query, buf);
        success = true;
    } finally {
        if (!success) {
            buf.release();
        }
    }
    out.add(new DatagramPacket(buf, recipient, null));
}
Also used : InetSocketAddress(java.net.InetSocketAddress) DatagramPacket(io.netty.channel.socket.DatagramPacket) ByteBuf(io.netty.buffer.ByteBuf)

Example 65 with DatagramPacket

use of io.netty.channel.socket.DatagramPacket in project netty by netty.

the class DnsQueryTest method testEncodeAndDecodeQuery.

@Test
public void testEncodeAndDecodeQuery() {
    InetSocketAddress addr = SocketUtils.socketAddress("8.8.8.8", 53);
    EmbeddedChannel writeChannel = new EmbeddedChannel(new DatagramDnsQueryEncoder());
    EmbeddedChannel readChannel = new EmbeddedChannel(new DatagramDnsQueryDecoder());
    List<DnsQuery> queries = new ArrayList<DnsQuery>(5);
    queries.add(new DatagramDnsQuery(null, addr, 1).setRecord(DnsSection.QUESTION, new DefaultDnsQuestion("1.0.0.127.in-addr.arpa", DnsRecordType.PTR)));
    queries.add(new DatagramDnsQuery(null, addr, 1).setRecord(DnsSection.QUESTION, new DefaultDnsQuestion("www.example.com", DnsRecordType.A)));
    queries.add(new DatagramDnsQuery(null, addr, 1).setRecord(DnsSection.QUESTION, new DefaultDnsQuestion("example.com", DnsRecordType.AAAA)));
    queries.add(new DatagramDnsQuery(null, addr, 1).setRecord(DnsSection.QUESTION, new DefaultDnsQuestion("example.com", DnsRecordType.MX)));
    queries.add(new DatagramDnsQuery(null, addr, 1).setRecord(DnsSection.QUESTION, new DefaultDnsQuestion("example.com", DnsRecordType.CNAME)));
    for (DnsQuery query : queries) {
        assertThat(query.count(DnsSection.QUESTION), is(1));
        assertThat(query.count(DnsSection.ANSWER), is(0));
        assertThat(query.count(DnsSection.AUTHORITY), is(0));
        assertThat(query.count(DnsSection.ADDITIONAL), is(0));
        assertTrue(writeChannel.writeOutbound(query));
        DatagramPacket packet = writeChannel.readOutbound();
        assertTrue(packet.content().isReadable());
        assertTrue(readChannel.writeInbound(packet));
        DnsQuery decodedDnsQuery = readChannel.readInbound();
        assertEquals(query, decodedDnsQuery);
        assertTrue(decodedDnsQuery.release());
        assertNull(writeChannel.readOutbound());
        assertNull(readChannel.readInbound());
    }
    assertFalse(writeChannel.finish());
    assertFalse(readChannel.finish());
}
Also used : InetSocketAddress(java.net.InetSocketAddress) DatagramPacket(io.netty.channel.socket.DatagramPacket) ArrayList(java.util.ArrayList) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) Test(org.junit.jupiter.api.Test)

Aggregations

DatagramPacket (io.netty.channel.socket.DatagramPacket)75 InetSocketAddress (java.net.InetSocketAddress)45 ByteBuf (io.netty.buffer.ByteBuf)38 Test (org.junit.Test)15 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)14 Channel (io.netty.channel.Channel)8 ChannelFuture (io.netty.channel.ChannelFuture)8 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)8 DatagramChannel (io.netty.channel.socket.DatagramChannel)8 ByteBuffer (java.nio.ByteBuffer)6 Test (org.junit.jupiter.api.Test)6 Bootstrap (io.netty.bootstrap.Bootstrap)5 DefaultAddressedEnvelope (io.netty.channel.DefaultAddressedEnvelope)5 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)5 NioDatagramChannel (io.netty.channel.socket.nio.NioDatagramChannel)5 InetAddress (java.net.InetAddress)5 SocketAddress (java.net.SocketAddress)5 ArrayList (java.util.ArrayList)5 CountDownLatch (java.util.concurrent.CountDownLatch)5 AddressedEnvelope (io.netty.channel.AddressedEnvelope)4