Search in sources :

Example 26 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 27 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 28 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 29 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)

Example 30 with DatagramPacket

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

the class OioDatagramChannel method doReadMessages.

@Override
protected int doReadMessages(List<Object> buf) throws Exception {
    DatagramChannelConfig config = config();
    final RecvByteBufAllocator.Handle allocHandle = unsafe().recvBufAllocHandle();
    ByteBuf data = config.getAllocator().heapBuffer(allocHandle.guess());
    boolean free = true;
    try {
        // Ensure we null out the address which may have been set before.
        tmpPacket.setAddress(null);
        tmpPacket.setData(data.array(), data.arrayOffset(), data.capacity());
        socket.receive(tmpPacket);
        InetSocketAddress remoteAddr = (InetSocketAddress) tmpPacket.getSocketAddress();
        allocHandle.lastBytesRead(tmpPacket.getLength());
        buf.add(new DatagramPacket(data.writerIndex(allocHandle.lastBytesRead()), localAddress(), remoteAddr));
        free = false;
        return 1;
    } catch (SocketTimeoutException e) {
        // Expected
        return 0;
    } catch (SocketException e) {
        if (!e.getMessage().toLowerCase(Locale.US).contains("socket closed")) {
            throw e;
        }
        return -1;
    } catch (Throwable cause) {
        PlatformDependent.throwException(cause);
        return -1;
    } finally {
        if (free) {
            data.release();
        }
    }
}
Also used : RecvByteBufAllocator(io.netty.channel.RecvByteBufAllocator) SocketException(java.net.SocketException) SocketTimeoutException(java.net.SocketTimeoutException) InetSocketAddress(java.net.InetSocketAddress) DatagramPacket(io.netty.channel.socket.DatagramPacket) DatagramChannelConfig(io.netty.channel.socket.DatagramChannelConfig) ByteBuf(io.netty.buffer.ByteBuf)

Aggregations

DatagramPacket (io.netty.channel.socket.DatagramPacket)74 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