Search in sources :

Example 31 with DatagramPacket

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

the class DatagramMulticastTest method testMulticast.

public void testMulticast(Bootstrap sb, Bootstrap cb) throws Throwable {
    NetworkInterface iface = multicastNetworkInterface();
    assumeTrue(iface != null, "No NetworkInterface found that supports multicast and " + socketInternetProtocalFamily());
    MulticastTestHandler mhandler = new MulticastTestHandler();
    sb.handler(new SimpleChannelInboundHandler<Object>() {

        @Override
        public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        // Nothing will be sent.
        }
    });
    cb.handler(mhandler);
    sb.option(ChannelOption.IP_MULTICAST_IF, iface);
    sb.option(ChannelOption.SO_REUSEADDR, true);
    cb.option(ChannelOption.IP_MULTICAST_IF, iface);
    cb.option(ChannelOption.SO_REUSEADDR, true);
    DatagramChannel sc = (DatagramChannel) sb.bind(newSocketAddress(iface)).sync().channel();
    assertEquals(iface, sc.config().getNetworkInterface());
    assertInterfaceAddress(iface, sc.config().getInterface());
    InetSocketAddress addr = sc.localAddress();
    cb.localAddress(addr.getPort());
    if (sc instanceof OioDatagramChannel) {
        // skip the test for OIO, as it fails because of
        // No route to host which makes no sense.
        // Maybe a JDK bug ?
        sc.close().awaitUninterruptibly();
        return;
    }
    DatagramChannel cc = (DatagramChannel) cb.bind().sync().channel();
    assertEquals(iface, cc.config().getNetworkInterface());
    assertInterfaceAddress(iface, cc.config().getInterface());
    InetSocketAddress groupAddress = SocketUtils.socketAddress(groupAddress(), addr.getPort());
    cc.joinGroup(groupAddress, iface).sync();
    sc.writeAndFlush(new DatagramPacket(Unpooled.copyInt(1), groupAddress)).sync();
    assertTrue(mhandler.await());
    // leave the group
    cc.leaveGroup(groupAddress, iface).sync();
    // sleep a second to make sure we left the group
    Thread.sleep(1000);
    // we should not receive a message anymore as we left the group before
    sc.writeAndFlush(new DatagramPacket(Unpooled.copyInt(1), groupAddress)).sync();
    mhandler.await();
    cc.config().setLoopbackModeDisabled(false);
    sc.config().setLoopbackModeDisabled(false);
    assertFalse(cc.config().isLoopbackModeDisabled());
    assertFalse(sc.config().isLoopbackModeDisabled());
    cc.config().setLoopbackModeDisabled(true);
    sc.config().setLoopbackModeDisabled(true);
    assertTrue(cc.config().isLoopbackModeDisabled());
    assertTrue(sc.config().isLoopbackModeDisabled());
    sc.close().awaitUninterruptibly();
    cc.close().awaitUninterruptibly();
}
Also used : InetSocketAddress(java.net.InetSocketAddress) OioDatagramChannel(io.netty.channel.socket.oio.OioDatagramChannel) DatagramPacket(io.netty.channel.socket.DatagramPacket) OioDatagramChannel(io.netty.channel.socket.oio.OioDatagramChannel) DatagramChannel(io.netty.channel.socket.DatagramChannel) NetworkInterface(java.net.NetworkInterface) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException)

Example 32 with DatagramPacket

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

the class DatagramUnicastInetTest method setupServerChannel.

@Override
protected Channel setupServerChannel(Bootstrap sb, final byte[] bytes, final SocketAddress sender, final CountDownLatch latch, final AtomicReference<Throwable> errorRef, final boolean echo) throws Throwable {
    sb.handler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) {
            ch.pipeline().addLast(new SimpleChannelInboundHandler<DatagramPacket>() {

                @Override
                public void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) {
                    try {
                        if (sender == null) {
                            assertNotNull(msg.sender());
                        } else {
                            InetSocketAddress senderAddress = (InetSocketAddress) sender;
                            if (senderAddress.getAddress().isAnyLocalAddress()) {
                                assertEquals(senderAddress.getPort(), msg.sender().getPort());
                            } else {
                                assertEquals(sender, msg.sender());
                            }
                        }
                        ByteBuf buf = msg.content();
                        assertEquals(bytes.length, buf.readableBytes());
                        for (int i = 0; i < bytes.length; i++) {
                            assertEquals(bytes[i], buf.getByte(buf.readerIndex() + i));
                        }
                        // Test that the channel's localAddress is equal to the message's recipient
                        assertEquals(ctx.channel().localAddress(), msg.recipient());
                        if (echo) {
                            ctx.writeAndFlush(new DatagramPacket(buf.retainedDuplicate(), msg.sender()));
                        }
                    } finally {
                        latch.countDown();
                    }
                }

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                    errorRef.compareAndSet(null, cause);
                }
            });
        }
    });
    return sb.bind(newSocketAddress()).sync().channel();
}
Also used : SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) InetSocketAddress(java.net.InetSocketAddress) Channel(io.netty.channel.Channel) DatagramChannel(io.netty.channel.socket.DatagramChannel) DatagramPacket(io.netty.channel.socket.DatagramPacket) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf)

Example 33 with DatagramPacket

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

the class KQueueDatagramChannel method filterOutboundMessage.

@Override
protected Object filterOutboundMessage(Object msg) {
    if (msg instanceof DatagramPacket) {
        DatagramPacket packet = (DatagramPacket) msg;
        ByteBuf content = packet.content();
        return UnixChannelUtil.isBufferCopyNeededForWrite(content) ? new DatagramPacket(newDirectBuffer(packet, content), packet.recipient()) : msg;
    }
    if (msg instanceof ByteBuf) {
        ByteBuf buf = (ByteBuf) msg;
        return UnixChannelUtil.isBufferCopyNeededForWrite(buf) ? newDirectBuffer(buf) : buf;
    }
    if (msg instanceof AddressedEnvelope) {
        @SuppressWarnings("unchecked") AddressedEnvelope<Object, SocketAddress> e = (AddressedEnvelope<Object, SocketAddress>) msg;
        if (e.content() instanceof ByteBuf && (e.recipient() == null || e.recipient() instanceof InetSocketAddress)) {
            ByteBuf content = (ByteBuf) e.content();
            return UnixChannelUtil.isBufferCopyNeededForWrite(content) ? new DefaultAddressedEnvelope<ByteBuf, InetSocketAddress>(newDirectBuffer(e, content), (InetSocketAddress) e.recipient()) : e;
        }
    }
    throw new UnsupportedOperationException("unsupported message type: " + StringUtil.simpleClassName(msg) + EXPECTED_TYPES);
}
Also used : DefaultAddressedEnvelope(io.netty.channel.DefaultAddressedEnvelope) AddressedEnvelope(io.netty.channel.AddressedEnvelope) InetSocketAddress(java.net.InetSocketAddress) DatagramPacket(io.netty.channel.socket.DatagramPacket) ByteBuf(io.netty.buffer.ByteBuf) SocketAddress(java.net.SocketAddress) DatagramSocketAddress(io.netty.channel.unix.DatagramSocketAddress) InetSocketAddress(java.net.InetSocketAddress)

Example 34 with DatagramPacket

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

the class EpollDatagramScatteringReadTest method testScatteringReadWithSmallBuffer0.

private void testScatteringReadWithSmallBuffer0(Bootstrap sb, Bootstrap cb, boolean connected) throws Throwable {
    int packetSize = 16;
    sb.option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(1400, 1400, 64 * 1024));
    sb.option(EpollChannelOption.MAX_DATAGRAM_PAYLOAD_SIZE, 1400);
    Channel sc = null;
    Channel cc = null;
    try {
        cb.handler(new SimpleChannelInboundHandler<Object>() {

            @Override
            public void channelRead0(ChannelHandlerContext ctx, Object msgs) {
            // Nothing will be sent.
            }
        });
        cc = cb.bind(newSocketAddress()).sync().channel();
        final SocketAddress ccAddress = cc.localAddress();
        final AtomicReference<Throwable> errorRef = new AtomicReference<Throwable>();
        final byte[] bytes = new byte[packetSize];
        PlatformDependent.threadLocalRandom().nextBytes(bytes);
        final CountDownLatch latch = new CountDownLatch(1);
        sb.handler(new SimpleChannelInboundHandler<DatagramPacket>() {

            @Override
            protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) {
                assertEquals(ccAddress, msg.sender());
                assertEquals(bytes.length, msg.content().readableBytes());
                byte[] receivedBytes = new byte[bytes.length];
                msg.content().readBytes(receivedBytes);
                assertArrayEquals(bytes, receivedBytes);
                latch.countDown();
            }

            @Override
            public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                errorRef.compareAndSet(null, cause);
            }
        });
        sc = sb.bind(newSocketAddress()).sync().channel();
        if (connected) {
            sc.connect(cc.localAddress()).syncUninterruptibly();
        }
        InetSocketAddress addr = (InetSocketAddress) sc.localAddress();
        cc.writeAndFlush(new DatagramPacket(cc.alloc().directBuffer().writeBytes(bytes), addr)).sync();
        if (!latch.await(10, TimeUnit.SECONDS)) {
            Throwable error = errorRef.get();
            if (error != null) {
                throw error;
            }
            fail("Timeout while waiting for packets");
        }
    } finally {
        if (cc != null) {
            cc.close().syncUninterruptibly();
        }
        if (sc != null) {
            sc.close().syncUninterruptibly();
        }
    }
}
Also used : InetSocketAddress(java.net.InetSocketAddress) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) AdaptiveRecvByteBufAllocator(io.netty.channel.AdaptiveRecvByteBufAllocator) DatagramPacket(io.netty.channel.socket.DatagramPacket) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress)

Example 35 with DatagramPacket

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

the class EpollDatagramScatteringReadTest method testScatteringRead.

private void testScatteringRead(Bootstrap sb, Bootstrap cb, boolean connected, boolean partial) throws Throwable {
    int packetSize = 512;
    int numPackets = 4;
    sb.option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(packetSize, packetSize * (partial ? numPackets / 2 : numPackets), 64 * 1024));
    sb.option(EpollChannelOption.MAX_DATAGRAM_PAYLOAD_SIZE, packetSize);
    Channel sc = null;
    Channel cc = null;
    try {
        cb.handler(new SimpleChannelInboundHandler<Object>() {

            @Override
            public void channelRead0(ChannelHandlerContext ctx, Object msgs) throws Exception {
            // Nothing will be sent.
            }
        });
        cc = cb.bind(newSocketAddress()).sync().channel();
        final SocketAddress ccAddress = cc.localAddress();
        final AtomicReference<Throwable> errorRef = new AtomicReference<Throwable>();
        final byte[] bytes = new byte[packetSize];
        PlatformDependent.threadLocalRandom().nextBytes(bytes);
        final CountDownLatch latch = new CountDownLatch(numPackets);
        sb.handler(new SimpleChannelInboundHandler<DatagramPacket>() {

            private int counter;

            @Override
            public void channelReadComplete(ChannelHandlerContext ctx) {
                assertTrue(counter > 1);
                counter = 0;
                ctx.read();
            }

            @Override
            protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) {
                assertEquals(ccAddress, msg.sender());
                assertEquals(bytes.length, msg.content().readableBytes());
                byte[] receivedBytes = new byte[bytes.length];
                msg.content().readBytes(receivedBytes);
                assertArrayEquals(bytes, receivedBytes);
                counter++;
                latch.countDown();
            }

            @Override
            public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                errorRef.compareAndSet(null, cause);
            }
        });
        sb.option(ChannelOption.AUTO_READ, false);
        sc = sb.bind(newSocketAddress()).sync().channel();
        if (connected) {
            sc.connect(cc.localAddress()).syncUninterruptibly();
        }
        InetSocketAddress addr = (InetSocketAddress) sc.localAddress();
        List<ChannelFuture> futures = new ArrayList<ChannelFuture>(numPackets);
        for (int i = 0; i < numPackets; i++) {
            futures.add(cc.write(new DatagramPacket(cc.alloc().directBuffer().writeBytes(bytes), addr)));
        }
        cc.flush();
        for (ChannelFuture f : futures) {
            f.sync();
        }
        // Enable autoread now which also triggers a read, this should cause scattering reads (recvmmsg) to happen.
        sc.config().setAutoRead(true);
        if (!latch.await(10, TimeUnit.SECONDS)) {
            Throwable error = errorRef.get();
            if (error != null) {
                throw error;
            }
            fail("Timeout while waiting for packets");
        }
    } finally {
        if (cc != null) {
            cc.close().syncUninterruptibly();
        }
        if (sc != null) {
            sc.close().syncUninterruptibly();
        }
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) InetSocketAddress(java.net.InetSocketAddress) Channel(io.netty.channel.Channel) ArrayList(java.util.ArrayList) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) AdaptiveRecvByteBufAllocator(io.netty.channel.AdaptiveRecvByteBufAllocator) DatagramPacket(io.netty.channel.socket.DatagramPacket) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress)

Aggregations

DatagramPacket (io.netty.channel.socket.DatagramPacket)85 InetSocketAddress (java.net.InetSocketAddress)48 ByteBuf (io.netty.buffer.ByteBuf)45 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)16 Test (org.junit.Test)15 Channel (io.netty.channel.Channel)9 DatagramChannel (io.netty.channel.socket.DatagramChannel)9 Test (org.junit.jupiter.api.Test)9 ChannelFuture (io.netty.channel.ChannelFuture)8 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)8 CountDownLatch (java.util.concurrent.CountDownLatch)8 Bootstrap (io.netty.bootstrap.Bootstrap)7 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)7 NioDatagramChannel (io.netty.channel.socket.nio.NioDatagramChannel)6 InetAddress (java.net.InetAddress)6 ByteBuffer (java.nio.ByteBuffer)6 DefaultAddressedEnvelope (io.netty.channel.DefaultAddressedEnvelope)5 SimpleChannelInboundHandler (io.netty.channel.SimpleChannelInboundHandler)5 SocketAddress (java.net.SocketAddress)5 SocketException (java.net.SocketException)5