Example usage for io.netty.channel.socket DatagramPacket DatagramPacket

List of usage examples for io.netty.channel.socket DatagramPacket DatagramPacket

Introduction

In this page you can find the example usage for io.netty.channel.socket DatagramPacket DatagramPacket.

Prototype

public DatagramPacket(ByteBuf data, InetSocketAddress recipient) 

Source Link

Document

Create a new instance with the specified packet data and recipient address.

Usage

From source file:org.aotorrent.common.connection.UDPTrackerConnection.java

License:Apache License

@Override
protected void obtainPeers() {
    try {/*from w  w w .j  a  v  a2  s  .  co m*/
        EventLoopGroup group = new NioEventLoopGroup();

        Bootstrap b = new Bootstrap();

        b.group(group).channel(NioDatagramChannel.class).handler(new ChannelInitializer<DatagramChannel>() {
            @Override
            protected void initChannel(DatagramChannel ch) throws Exception {
                final ChannelPipeline p = ch.pipeline();
                p.addLast(new TrackerConnectionHandler());
            }
        });

        Channel ch = b.bind(0).sync().channel();

        transactionId = RANDOM.nextInt();
        LOGGER.debug("Sending connect request to " + address);
        ch.writeAndFlush(new DatagramPacket(new UDPConnectRequest(transactionId).toTransmit(), address));

        ch.closeFuture().sync();
    } catch (InterruptedException e) {
        LOGGER.error("Tracker connection interrupted");
    }

}

From source file:org.apache.camel.component.netty4.codec.DatagramPacketEncoder.java

License:Apache License

@Override
protected void encode(ChannelHandlerContext ctx, AddressedEnvelope<Object, InetSocketAddress> msg,
        List<Object> out) throws Exception {
    if (msg.content() instanceof ByteBuf) {
        ByteBuf payload = (ByteBuf) msg.content();
        // Just wrap the message as DatagramPacket, need to make sure the message content is ByteBuf
        DatagramPacket dp = new DatagramPacket(payload.retain(), msg.recipient());
        out.add(dp);/*  w w  w. ja  v  a 2s . c  o  m*/
    }
}

From source file:org.apache.directory.server.dhcp.netty.Dhcp6Handler.java

@Override
protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Incomming DHCP : {}, from: {}", ByteBufUtil.hexDump(msg.content()), msg.sender());
    }// w  w  w  .j  av  a  2s . co  m

    final Dhcp6Message incommingMsg;
    try {
        incommingMsg = dhcp6MessageDecoder.decode(msg.content().nioBuffer());
    } catch (final Dhcp6Exception.UnknownMsgException e) {
        LOG.warn("Unknown DHCP message type: {}. Ignoring", ByteBufUtil.hexDump(msg.content()), e);
        return;
    }

    final Optional<Dhcp6Message> reply = dhcpService
            .getReplyFor(new Dhcp6RequestContext(msg.sender().getAddress()), incommingMsg);

    if (reply.isPresent()) {
        LOG.debug("Responding with message: {}", reply.get());

        // TODO what size to allocate the buffer to ?
        ByteBuf buf = ctx.alloc().buffer(1024);
        ByteBuffer buffer = buf.nioBuffer(buf.writerIndex(), buf.writableBytes());
        dhcp6MessageEncoder.encode(buffer, reply.get());
        buffer.flip();
        buf.writerIndex(buf.writerIndex() + buffer.remaining());
        DatagramPacket packet = new DatagramPacket(buf, msg.sender());
        ctx.write(packet);
    } else {
        LOG.warn("No response from DHCP service received for: {}. Ignoring.", incommingMsg);
    }
}

From source file:org.apache.directory.server.dhcp.netty.DhcpHandler.java

@Override
protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
    DhcpMessage request = decoder.decode(msg.content().nioBuffer());

    DhcpRequestContext context = interfaceManager.newRequestContext(
            (InetSocketAddress) ctx.channel().localAddress(), msg.sender(), msg.recipient(), request);
    if (context == null) {
        debug("IGNQUERY", msg.sender(), msg.recipient(), request);
        return;//  w w  w .j  av a 2s  .  co  m
    }
    // debug("READ", msg.sender(), msg.recipient(), request);

    MDCUtils.init(context, request);
    try {
        DhcpMessage reply = dhcpService.getReplyFor(context, request);
        if (reply == null) {
            debug("NOREPLY", msg.sender(), msg.recipient(), request);
            return;
        }

        InterfaceAddress localAddress = interfaceManager.getResponseInterface(request.getRelayAgentAddress(),
                request.getCurrentClientAddress(), msg.sender().getAddress(), reply);
        if (localAddress == null) {
            debug("NOIFACE", msg.recipient(), msg.sender(), reply);
            return;
        }

        debug("READ", msg.sender(), msg.recipient(), request);

        InetSocketAddress isa = DhcpInterfaceUtils.determineMessageDestination(request, reply, localAddress,
                msg.sender().getPort());

        ByteBuf buf = ctx.alloc().buffer(1024);
        ByteBuffer buffer = buf.nioBuffer(buf.writerIndex(), buf.writableBytes());
        encoder.encode(buffer, reply);
        buffer.flip();
        buf.writerIndex(buf.writerIndex() + buffer.remaining());
        DatagramPacket packet = new DatagramPacket(buf, isa);
        debug("WRITE", packet.sender(), packet.recipient(), reply);
        ctx.write(packet, ctx.voidPromise());
    } finally {
        MDCUtils.fini();
    }
}

From source file:org.apache.kerby.kerberos.kdc.impl.NettyKdcUdpServerHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, DatagramPacket datagramPacket)
        throws Exception {
    ByteBuf byteBuf = datagramPacket.content();
    byte[] msgBytes = new byte[byteBuf.readableBytes()];
    byteBuf.readBytes(msgBytes);/*w  w w .j  a  v  a2 s.  c om*/
    ByteBuffer requestMessage = ByteBuffer.wrap(msgBytes);
    InetSocketAddress clientAddress = datagramPacket.sender();

    boolean isTcp = false;
    try {
        ByteBuffer responseMessage = myKdcHandler.handleMessage(requestMessage, isTcp,
                clientAddress.getAddress());
        channelHandlerContext
                .writeAndFlush(new DatagramPacket(Unpooled.wrappedBuffer(responseMessage), clientAddress));
    } catch (Exception e) {
        LOG.error("Error occurred while processing request:" + e.getMessage());
    }
}

From source file:org.codice.alliance.distribution.sdk.video.stream.mpegts.MpegTsUdpClient.java

License:Open Source License

private static void transmit(Channel ch, byte[] buf, String ip, int port) throws InterruptedException {
    ChannelFuture cf = ch/*from   w  w w.j a v a2 s  .  c o  m*/
            .writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(buf), new InetSocketAddress(ip, port)));
    cf.await();
}

From source file:org.graylog2.gelfclient.encoder.GelfMessageUdpEncoder.java

License:Apache License

/**
 * {@inheritDoc}//from w  w  w  . j  a  v a  2 s  . co m
 */
@Override
protected void encode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> out) throws Exception {
    // Need to retain() the buffer here to avoid a io.netty.util.IllegalReferenceCountException.
    out.add(new DatagramPacket(buf.retain(), remoteAddress));
}

From source file:org.hawkular.metrics.clients.ptrans.collectd.packet.CollectdPacketDecoderTest.java

License:Apache License

@Test
public void handlerShouldNotOutputCollectdPacketWhenNoPartIsDecoded() {
    DatagramPacket datagramPacket = new DatagramPacket(Unpooled.buffer(), DUMMY_ADDRESS);
    EmbeddedChannel channel = new EmbeddedChannel(new CollectdPacketDecoder());
    assertFalse("Expected no CollectdPacket", channel.writeInbound(datagramPacket));
}

From source file:org.hawkular.metrics.clients.ptrans.collectd.packet.CollectdPacketDecoderTest.java

License:Apache License

@Test
public void handlerShouldDecodePacketsInOrder() {
    int numberOfPartTypes = PartType.values().length;
    int numberOfParts = numberOfPartTypes * 50;

    List<Part> parts = new ArrayList<>(numberOfParts);
    for (int i = 0; i < numberOfParts; i++) {
        PartType partType = PartType.values()[i % numberOfPartTypes];
        switch (partType) {
        case HOST:
        case PLUGIN:
        case PLUGIN_INSTANCE:
        case TYPE:
        case INSTANCE:
            parts.add(new StringPart(partType, "marseille"));
            break;
        case TIME:
        case TIME_HIGH_RESOLUTION:
        case INTERVAL:
        case INTERVAL_HIGH_RESOLUTION:
            parts.add(new NumericPart(partType, 13L));
            break;
        case VALUES:
            parts.add(new ValuePart(partType, newValuesInstance()));
            break;
        default://  w  ww  . jav a  2 s  . c  om
            fail("Unknown part type: " + partType);
        }
    }
    Collections.shuffle(parts);

    ByteBuf buffer = Unpooled.buffer();
    for (Part part : parts) {
        PartType partType = part.getPartType();
        switch (partType) {
        case HOST:
        case PLUGIN:
        case PLUGIN_INSTANCE:
        case TYPE:
        case INSTANCE:
            buffer.writeBytes(createStringPartBuffer((String) part.getValue(), partType));
            break;
        case TIME:
        case TIME_HIGH_RESOLUTION:
        case INTERVAL:
        case INTERVAL_HIGH_RESOLUTION:
            buffer.writeBytes(createNumericPartBuffer((Long) part.getValue(), partType));
            break;
        case VALUES:
            buffer.writeBytes(createValuesPartBuffer((Values) part.getValue()));
            break;
        default:
            fail("Unknown part type: " + partType);
        }
    }

    DatagramPacket datagramPacket = new DatagramPacket(buffer, DUMMY_ADDRESS);
    EmbeddedChannel channel = new EmbeddedChannel(new CollectdPacketDecoder());
    assertTrue("Expected CollectdPacket", channel.writeInbound(datagramPacket));

    Object output = channel.readInbound();
    assertEquals(CollectdPacket.class, output.getClass());

    CollectdPacket collectdPacket = (CollectdPacket) output;
    List<Part> partsResult = collectdPacket.getParts();
    assertEquals("Wrong number of parts in the packet", numberOfParts, partsResult.size());
    assertEquals("Wrong packet order", toPartTypeList(parts), toPartTypeList(partsResult));

    assertNull("Expected just one CollectdPacket", channel.readInbound());
}

From source file:org.hawkular.metrics.clients.ptrans.collectd.packet.PacketDecodingTest.java

License:Apache License

private void shouldDecodePart(PartType partType, ByteBuf buffer, Class<? extends Part> partClass,
        Matcher<Object> matcher) {

    DatagramPacket datagramPacket = new DatagramPacket(buffer.duplicate(), DUMMY_ADDRESS);

    EmbeddedChannel channel = new EmbeddedChannel(new CollectdPacketDecoder());
    assertTrue("Expected a CollectdPacket", channel.writeInbound(datagramPacket));

    Object output = channel.readInbound();
    assertEquals(CollectdPacket.class, output.getClass());

    CollectdPacket collectdPacket = (CollectdPacket) output;
    List<Part> parts = collectdPacket.getParts();
    assertEquals("Expected only one part in the packet", 1, parts.size());

    Part part = parts.iterator().next();
    assertEquals(partClass, part.getClass());
    assertEquals(partType, part.getPartType());
    assertThat(part.getValue(), matcher);

    assertNull("Expected just one CollectdPacket", channel.readInbound());
}