Search in sources :

Example 36 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)

Example 37 with DatagramPacket

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

the class NioDatagramChannel method doReadMessages.

@Override
protected int doReadMessages(List<Object> buf) throws Exception {
    DatagramChannel ch = javaChannel();
    DatagramChannelConfig config = config();
    RecvByteBufAllocator.Handle allocHandle = unsafe().recvBufAllocHandle();
    ByteBuf data = allocHandle.allocate(config.getAllocator());
    allocHandle.attemptedBytesRead(data.writableBytes());
    boolean free = true;
    try {
        ByteBuffer nioData = data.internalNioBuffer(data.writerIndex(), data.writableBytes());
        int pos = nioData.position();
        InetSocketAddress remoteAddress = (InetSocketAddress) ch.receive(nioData);
        if (remoteAddress == null) {
            return 0;
        }
        allocHandle.lastBytesRead(nioData.position() - pos);
        buf.add(new DatagramPacket(data.writerIndex(data.writerIndex() + allocHandle.lastBytesRead()), localAddress(), remoteAddress));
        free = false;
        return 1;
    } catch (Throwable cause) {
        PlatformDependent.throwException(cause);
        return -1;
    } finally {
        if (free) {
            data.release();
        }
    }
}
Also used : RecvByteBufAllocator(io.netty.channel.RecvByteBufAllocator) InetSocketAddress(java.net.InetSocketAddress) DatagramPacket(io.netty.channel.socket.DatagramPacket) DatagramChannel(java.nio.channels.DatagramChannel) DatagramChannelConfig(io.netty.channel.socket.DatagramChannelConfig) ByteBuf(io.netty.buffer.ByteBuf) ByteBuffer(java.nio.ByteBuffer)

Example 38 with DatagramPacket

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

the class PcapWriteHandlerTest method udpV4.

@Test
public void udpV4() throws InterruptedException {
    ByteBuf byteBuf = Unpooled.buffer();
    InetSocketAddress srvReqAddr = new InetSocketAddress("127.0.0.1", 0);
    InetSocketAddress cltReqAddr = new InetSocketAddress("127.0.0.1", 0);
    NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup(2);
    // We'll bootstrap a UDP Server to avoid "Network Unreachable errors" when sending UDP Packet.
    Bootstrap server = new Bootstrap().group(eventLoopGroup).channel(NioDatagramChannel.class).handler(new SimpleChannelInboundHandler<DatagramPacket>() {

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) {
        // Discard
        }
    });
    ChannelFuture channelFutureServer = server.bind(srvReqAddr).sync();
    assertTrue(channelFutureServer.isSuccess());
    // We'll bootstrap a UDP Client for sending UDP Packets to UDP Server.
    Bootstrap client = new Bootstrap().group(eventLoopGroup).channel(NioDatagramChannel.class).handler(new PcapWriteHandler(new ByteBufOutputStream(byteBuf)));
    ChannelFuture channelFutureClient = client.connect(channelFutureServer.channel().localAddress(), cltReqAddr).sync();
    assertTrue(channelFutureClient.isSuccess());
    Channel clientChannel = channelFutureClient.channel();
    assertTrue(clientChannel.writeAndFlush(Unpooled.wrappedBuffer("Meow".getBytes())).sync().isSuccess());
    assertTrue(eventLoopGroup.shutdownGracefully().sync().isSuccess());
    // Verify Pcap Global Headers
    verifyGlobalHeaders(byteBuf);
    // Verify Pcap Packet Header
    // Just read, we don't care about timestamps for now
    byteBuf.readInt();
    // Just read, we don't care about timestamps for now
    byteBuf.readInt();
    // Length of Packet Saved In Pcap
    assertEquals(46, byteBuf.readInt());
    // Actual Length of Packet
    assertEquals(46, byteBuf.readInt());
    // -------------------------------------------- Verify Packet --------------------------------------------
    // Verify Ethernet Packet
    ByteBuf ethernetPacket = byteBuf.readBytes(46);
    ByteBuf dstMac = ethernetPacket.readBytes(6);
    ByteBuf srcMac = ethernetPacket.readBytes(6);
    assertArrayEquals(new byte[] { 0, 0, 94, 0, 83, -1 }, ByteBufUtil.getBytes(dstMac));
    assertArrayEquals(new byte[] { 0, 0, 94, 0, 83, 0 }, ByteBufUtil.getBytes(srcMac));
    assertEquals(0x0800, ethernetPacket.readShort());
    // Verify IPv4 Packet
    ByteBuf ipv4Packet = ethernetPacket.readBytes(32);
    // Version + IHL
    assertEquals(0x45, ipv4Packet.readByte());
    // DSCP
    assertEquals(0x00, ipv4Packet.readByte());
    // Length
    assertEquals(32, ipv4Packet.readShort());
    // Identification
    assertEquals(0x0000, ipv4Packet.readShort());
    // Fragment
    assertEquals(0x0000, ipv4Packet.readShort());
    // TTL
    assertEquals((byte) 0xff, ipv4Packet.readByte());
    // Protocol
    assertEquals((byte) 17, ipv4Packet.readByte());
    // Checksum
    assertEquals(0, ipv4Packet.readShort());
    InetSocketAddress localAddr = (InetSocketAddress) clientChannel.remoteAddress();
    // Source IPv4 Address
    assertEquals(NetUtil.ipv4AddressToInt((Inet4Address) localAddr.getAddress()), ipv4Packet.readInt());
    InetSocketAddress remoteAddr = (InetSocketAddress) clientChannel.localAddress();
    // Destination IPv4 Address
    assertEquals(NetUtil.ipv4AddressToInt((Inet4Address) remoteAddr.getAddress()), ipv4Packet.readInt());
    // Verify UDP Packet
    ByteBuf udpPacket = ipv4Packet.readBytes(12);
    // Source Port
    assertEquals(remoteAddr.getPort() & 0xffff, udpPacket.readUnsignedShort());
    // Destination Port
    assertEquals(localAddr.getPort() & 0xffff, udpPacket.readUnsignedShort());
    // Length
    assertEquals(12, udpPacket.readShort());
    // Checksum
    assertEquals(0x0001, udpPacket.readShort());
    // Verify Payload
    ByteBuf payload = udpPacket.readBytes(4);
    // Payload
    assertArrayEquals("Meow".getBytes(CharsetUtil.UTF_8), ByteBufUtil.getBytes(payload));
    // Release all ByteBuf
    assertTrue(dstMac.release());
    assertTrue(srcMac.release());
    assertTrue(payload.release());
    assertTrue(byteBuf.release());
    assertTrue(ethernetPacket.release());
    assertTrue(ipv4Packet.release());
    assertTrue(udpPacket.release());
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) Inet4Address(java.net.Inet4Address) ByteBufOutputStream(io.netty.buffer.ByteBufOutputStream) InetSocketAddress(java.net.InetSocketAddress) NioDatagramChannel(io.netty.channel.socket.nio.NioDatagramChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Channel(io.netty.channel.Channel) NioDatagramChannel(io.netty.channel.socket.nio.NioDatagramChannel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) DatagramPacket(io.netty.channel.socket.DatagramPacket) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Test(org.junit.jupiter.api.Test)

Example 39 with DatagramPacket

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

the class QueryTest method testChannelRead.

private void testChannelRead(QueryHandler handler, byte[] recv, byte[] send) throws Exception {
    ChannelHandlerContext ctx = mock(ChannelHandlerContext.class);
    ByteBufAllocator alloc = mock(ByteBufAllocator.class);
    when(ctx.alloc()).thenReturn(alloc);
    when(alloc.buffer()).thenReturn(Unpooled.buffer());
    DatagramPacket packet = new DatagramPacket(Unpooled.wrappedBuffer(recv), null, address);
    handler.channelRead(ctx, packet);
    verify(ctx).write(argThat(new DatagramPacketMatcher(send)));
}
Also used : ByteBufAllocator(io.netty.buffer.ByteBufAllocator) DatagramPacket(io.netty.channel.socket.DatagramPacket) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext)

Example 40 with DatagramPacket

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

the class UdpClientTest method testUdpClientTimeout.

@Test
public void testUdpClientTimeout() throws Exception {
    int port = choosePort();
    UdpServer<DatagramPacket, DatagramPacket> server = new HelloUdpServer(port, 5000).createServer();
    server.start();
    BaseLoadBalancer lb = new BaseLoadBalancer();
    Server myServer = new Server("localhost", port);
    lb.setServersList(Lists.newArrayList(myServer));
    MyUDPClient client = new MyUDPClient(lb, DefaultClientConfigImpl.getClientConfigWithDefaultValues());
    try {
        String response = client.submit("Is there anybody out there?").map(new Func1<DatagramPacket, String>() {

            @Override
            public String call(DatagramPacket datagramPacket) {
                return datagramPacket.content().toString(Charset.defaultCharset());
            }
        }).toBlocking().first();
        fail("Exception expected");
    } catch (Exception e) {
        assertTrue(e.getCause() instanceof TimeoutException);
        assertEquals(1, client.getLoadBalancerContext().getServerStats(myServer).getSuccessiveConnectionFailureCount());
    } finally {
        server.shutdown();
    }
}
Also used : MyUDPClient(com.netflix.ribbon.transport.netty.MyUDPClient) Server(com.netflix.loadbalancer.Server) UdpServer(io.reactivex.netty.protocol.udp.server.UdpServer) DatagramPacket(io.netty.channel.socket.DatagramPacket) BaseLoadBalancer(com.netflix.loadbalancer.BaseLoadBalancer) TimeoutException(java.util.concurrent.TimeoutException) SocketException(java.net.SocketException) TimeoutException(java.util.concurrent.TimeoutException) Test(org.junit.Test)

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