Search in sources :

Example 71 with DatagramPacket

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

the class EpollDatagramChannel method recvmsg.

private boolean recvmsg(EpollRecvByteAllocatorHandle allocHandle, NativeDatagramPacketArray array, ByteBuf byteBuf) throws IOException {
    RecyclableArrayList datagramPackets = null;
    try {
        int writable = byteBuf.writableBytes();
        boolean added = array.addWritable(byteBuf, byteBuf.writerIndex(), writable);
        assert added;
        allocHandle.attemptedBytesRead(writable);
        NativeDatagramPacketArray.NativeDatagramPacket msg = array.packets()[0];
        int bytesReceived = socket.recvmsg(msg);
        if (bytesReceived == 0) {
            allocHandle.lastBytesRead(-1);
            return false;
        }
        byteBuf.writerIndex(bytesReceived);
        InetSocketAddress local = localAddress();
        DatagramPacket packet = msg.newDatagramPacket(byteBuf, local);
        if (!(packet instanceof io.netty.channel.unix.SegmentedDatagramPacket)) {
            processPacket(pipeline(), allocHandle, bytesReceived, packet);
            byteBuf = null;
        } else {
            // Its important that we process all received data out of the NativeDatagramPacketArray
            // before we call fireChannelRead(...). This is because the user may call flush()
            // in a channelRead(...) method and so may re-use the NativeDatagramPacketArray again.
            datagramPackets = RecyclableArrayList.newInstance();
            addDatagramPacketToOut(packet, datagramPackets);
            // null out byteBuf as addDatagramPacketToOut did take ownership of the ByteBuf / packet and transfered
            // it into the RecyclableArrayList.
            byteBuf = null;
            processPacketList(pipeline(), allocHandle, bytesReceived, datagramPackets);
            datagramPackets.recycle();
            datagramPackets = null;
        }
        return true;
    } finally {
        releaseAndRecycle(byteBuf, datagramPackets);
    }
}
Also used : RecyclableArrayList(io.netty.util.internal.RecyclableArrayList) InetSocketAddress(java.net.InetSocketAddress) DatagramPacket(io.netty.channel.socket.DatagramPacket)

Example 72 with DatagramPacket

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

the class EpollDatagramChannel method addDatagramPacketToOut.

private static void addDatagramPacketToOut(DatagramPacket packet, RecyclableArrayList out) {
    if (packet instanceof io.netty.channel.unix.SegmentedDatagramPacket) {
        io.netty.channel.unix.SegmentedDatagramPacket segmentedDatagramPacket = (io.netty.channel.unix.SegmentedDatagramPacket) packet;
        ByteBuf content = segmentedDatagramPacket.content();
        InetSocketAddress recipient = segmentedDatagramPacket.recipient();
        InetSocketAddress sender = segmentedDatagramPacket.sender();
        int segmentSize = segmentedDatagramPacket.segmentSize();
        do {
            out.add(new DatagramPacket(content.readRetainedSlice(Math.min(content.readableBytes(), segmentSize)), recipient, sender));
        } while (content.isReadable());
        segmentedDatagramPacket.release();
    } else {
        out.add(packet);
    }
}
Also used : InetSocketAddress(java.net.InetSocketAddress) DatagramPacket(io.netty.channel.socket.DatagramPacket) ByteBuf(io.netty.buffer.ByteBuf)

Example 73 with DatagramPacket

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

the class EpollDatagramUnicastTest method testSegmentedDatagramPacket.

private void testSegmentedDatagramPacket(Bootstrap sb, Bootstrap cb, boolean composite, boolean gro) throws Throwable {
    if (!(cb.group() instanceof EpollEventLoopGroup)) {
        // Only supported for the native epoll transport.
        return;
    }
    if (gro && !(sb.group() instanceof EpollEventLoopGroup)) {
        // Only supported for the native epoll transport.
        return;
    }
    assumeTrue(EpollDatagramChannel.isSegmentedDatagramPacketSupported());
    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 int numBuffers = 16;
        final int segmentSize = 512;
        int bufferCapacity = numBuffers * segmentSize;
        final CountDownLatch latch = new CountDownLatch(numBuffers);
        AtomicReference<Throwable> errorRef = new AtomicReference<Throwable>();
        if (gro) {
            // Enable GRO and also ensure we can read everything with one read as otherwise
            // we will drop things on the floor.
            sb.option(EpollChannelOption.UDP_GRO, true);
            sb.option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(bufferCapacity));
        }
        sc = sb.handler(new SimpleChannelInboundHandler<DatagramPacket>() {

            @Override
            public void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) {
                if (packet.content().readableBytes() == segmentSize) {
                    latch.countDown();
                }
            }
        }).bind(newSocketAddress()).sync().channel();
        if (sc instanceof EpollDatagramChannel) {
            assertEquals(gro, sc.config().getOption(EpollChannelOption.UDP_GRO));
        }
        InetSocketAddress addr = sendToAddress((InetSocketAddress) sc.localAddress());
        final ByteBuf buffer;
        if (composite) {
            CompositeByteBuf compositeBuffer = Unpooled.compositeBuffer();
            for (int i = 0; i < numBuffers; i++) {
                compositeBuffer.addComponent(true, Unpooled.directBuffer(segmentSize).writeZero(segmentSize));
            }
            buffer = compositeBuffer;
        } else {
            buffer = Unpooled.directBuffer(bufferCapacity).writeZero(bufferCapacity);
        }
        cc.writeAndFlush(new io.netty.channel.unix.SegmentedDatagramPacket(buffer, segmentSize, addr)).sync();
        if (!latch.await(10, TimeUnit.SECONDS)) {
            Throwable error = errorRef.get();
            if (error != null) {
                throw error;
            }
            fail();
        }
    } finally {
        if (cc != null) {
            cc.close().sync();
        }
        if (sc != null) {
            sc.close().sync();
        }
    }
}
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) CompositeByteBuf(io.netty.buffer.CompositeByteBuf) ByteBuf(io.netty.buffer.ByteBuf) CompositeByteBuf(io.netty.buffer.CompositeByteBuf) DatagramPacket(io.netty.channel.socket.DatagramPacket) FixedRecvByteBufAllocator(io.netty.channel.FixedRecvByteBufAllocator)

Example 74 with DatagramPacket

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

the class UDPChannel method sendPacket.

void sendPacket(byte[] wire, InetSocketAddress address) {
    DatagramPacket packet = new DatagramPacket(Unpooled.copiedBuffer(wire), address);
    channel.write(packet);
    channel.flush();
}
Also used : DatagramPacket(io.netty.channel.socket.DatagramPacket)

Example 75 with DatagramPacket

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

the class UdpClient method main.

public static void main(String[] args) {
    HydraClient client = new Client.Builder("localhost", 8888, new UdpClientProtocol()).useUDP(true).option(ChannelOption.SO_BROADCAST, true).build();
    if (client.isConnected()) {
        session = client.getSession();
        System.out.println("\nClient is online!");
        System.out.printf("Socket address: %s%n", session.getAddress());
    }
    System.out.println(session);
    try {
        session.getChannel().writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer("QOTM?", CharsetUtil.UTF_8), SocketUtils.socketAddress("localhost", 8888))).sync();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    // Send something simple
    session.send("This is a String and dealt with as object by Hydra");
}
Also used : HydraClient(de.datasecs.hydra.client.HydraClient) DatagramPacket(io.netty.channel.socket.DatagramPacket) HydraClient(de.datasecs.hydra.client.HydraClient) Client(de.datasecs.hydra.client.Client)

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