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

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

Introduction

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

Prototype

ByteBuf content();

Source Link

Document

Return the data which is held by this ByteBufHolder .

Usage

From source file:org.opendaylight.usc.plugin.UscFrameDecoderUdp.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, DatagramPacket msg, List<Object> out) throws Exception {

    ByteBuf buf = msg.content();
    log.trace("UscFrameDecoderUdp.decode " + buf);

    if (buf == null) {
        return;//from   w  ww.ja  va2s . c o m
    }

    out.add(UscFrame.getFromByteBuf(buf));
}

From source file:org.opendaylight.usc.test.EchoServerUdpHandler.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
    LOG.trace("channelRead0: " + msg);
    DatagramPacket reply = new DatagramPacket(msg.content().copy(), msg.sender());
    ctx.writeAndFlush(reply);/*from  w  ww  . j a  va  2 s . c  om*/

}

From source file:org.restcomm.imscf.common.lwcomm.service.impl.LwCommListenerHandler.java

License:Open Source License

public void channelRead0(ChannelHandlerContext context, DatagramPacket packet) throws Exception {
    long nanoBegin = System.nanoTime();
    try {//from   www .j  a va  2s  .  c  om
        MDC.put(LwCommUtil.LOGGER_MDC_MSGID_KEY, "unknown");
        // TODO: content will be truncated at the receive buffer size. See LwCommListener.start()
        String content = packet.content().toString(CharsetUtil.UTF_8);
        LwCommServiceImpl.LOGGER.trace("Message got from {}, content:\n{}", packet.sender(), content);
        LwCommMessage message = new LwCommMessage(content);
        MDC.put(LwCommUtil.LOGGER_MDC_MSGID_KEY, message.getId());
        LwCommServiceImpl.LOGGER.debug("LwCommHandler.channelRead0 - thread: {}", Thread.currentThread());
        switch (message.getType()) {
        case NORMAL:
            handleNormalMessage(message, content, context);
            break;
        case ACK:
            handleAck(message, content);
            break;
        case NACK:
            handleNack(message);
            break;
        case HEARTBEAT:
            LwCommServiceImpl.LOGGER.debug("heartbeat from {}", message.getFrom());
            LwCommServiceImpl.getServiceImpl().getNodeCatalog().heartbeatFromNode(message.getFrom());
            LwCommServiceImpl.getServiceImpl().getStatistics().incReceivedHeartbeatCount();
            break;
        case INVALID:
            LwCommServiceImpl.LOGGER.warn("invalid message: {}", content);
            LwCommServiceImpl.getServiceImpl().getStatistics().incInvalidMessageCount();
            break;
        default:
            LwCommServiceImpl.LOGGER.error("Unexpected message type: {}", message.getType());
            break;
        }
    } finally {
        long nanoEnd = System.nanoTime();
        long delay = (nanoEnd - nanoBegin) / 1000;
        LwCommServiceImpl.getServiceImpl().getStatistics().timeSpentInChannelRead0(delay);
        LwCommServiceImpl.LOGGER.debug("Receive handler took: {}us.", delay);
    }
}

From source file:org.restcomm.media.control.mgcp.network.netty.MgcpMessageDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, DatagramPacket msg, List<Object> out) throws Exception {
    final ByteBuf content = msg.content();
    final InetSocketAddress recipient = msg.recipient();
    final InetSocketAddress sender = msg.sender();

    // Get data from buffer
    byte[] payload = new byte[content.readableBytes()];
    content.getBytes(0, payload);/*from w w w .  j ava2  s .  com*/

    // Check message type based on first byte
    byte b = payload[0];

    // Produce message according to type
    MgcpMessage message;
    if (b >= 48 && b <= 57) {
        message = handleResponse(payload);
    } else {
        message = handleRequest(payload);
    }

    if (log.isDebugEnabled()) {
        log.debug("Incoming MGCP message from " + sender.toString() + ":\n\n" + message.toString() + "\n");
    }

    MgcpMessageEnvelope envelope = new MgcpMessageEnvelope(message, recipient, sender);

    // Pass message to next handler
    out.add(envelope);
}

From source file:org.rhq.metrics.netty.collectd.packet.CollectdPacketDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext context, DatagramPacket packet, List<Object> out) throws Exception {
    long start = System.currentTimeMillis();
    ByteBuf content = packet.content();
    List<Part> parts = new ArrayList<Part>(100);
    for (;;) {/* w w  w  . ja  v  a  2 s  . c o m*/
        if (!hasReadableBytes(content, 4)) {
            break;
        }
        short partTypeId = content.readShort();
        PartType partType = PartType.findById(partTypeId);
        int partLength = content.readUnsignedShort();
        int valueLength = partLength - 4;
        if (!hasReadableBytes(content, valueLength)) {
            break;
        }
        if (partType == null) {
            content.skipBytes(valueLength);
            continue;
        }
        Part part;
        switch (partType) {
        case HOST:
        case PLUGIN:
        case PLUGIN_INSTANCE:
        case TYPE:
        case INSTANCE:
            part = new StringPart(partType, readStringPartContent(content, valueLength));
            break;
        case TIME:
        case TIME_HIGH_RESOLUTION:
        case INTERVAL:
        case INTERVAL_HIGH_RESOLUTION:
            part = new NumericPart(partType, readNumericPartContent(content));
            break;
        case VALUES:
            part = new ValuePart(partType, readValuePartContent(content, valueLength));
            break;
        default:
            part = null;
            content.skipBytes(valueLength);
        }
        //noinspection ConstantConditions
        if (part != null) {
            logger.trace("Decoded part: {}", part);
            parts.add(part);
        }
    }

    if (logger.isTraceEnabled()) {
        long stop = System.currentTimeMillis();
        logger.trace("Decoded datagram in {} ms", stop - start);
    }

    if (parts.size() > 0) {
        CollectdPacket collectdPacket = new CollectdPacket(parts.toArray(new Part[parts.size()]));
        out.add(collectdPacket);
    } else {
        logger.debug("No parts decoded, no CollectdPacket output");
    }
}

From source file:org.traccar.handler.NetworkMessageHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (ctx.channel() instanceof DatagramChannel) {
        DatagramPacket packet = (DatagramPacket) msg;
        ctx.fireChannelRead(new NetworkMessage(packet.content(), packet.sender()));
    } else if (msg instanceof ByteBuf) {
        ByteBuf buffer = (ByteBuf) msg;/*from ww  w  .ja v  a  2 s .  co  m*/
        ctx.fireChannelRead(new NetworkMessage(buffer, ctx.channel().remoteAddress()));
    }
}

From source file:qotm.QuoteOfTheMomentServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
    System.err.println(packet);//w  w w .ja v a 2 s  .co  m
    if ("Hello".equals(packet.content().toString(CharsetUtil.UTF_8).substring(0, 5))) {
        ctx.write(new DatagramPacket(Unpooled.copiedBuffer(": " + nextQuote(), CharsetUtil.UTF_8),
                packet.sender()));
    }
}

From source file:ru.jts.authserver.network.handler.AuthClientsChannelHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
    Client client = ClientManger.getInstance().getClientCreateIfNeed(packet.sender(), ctx.channel());

    ByteBuf buf = packet.content().order(ByteOrder.LITTLE_ENDIAN);

    ClientPacket<Client> clientPacket = client.getPacketHandler().handlePacket(buf);
    if (clientPacket != null) {
        clientPacket.setClient(client);//  w w  w. ja  v  a 2s  .  c o  m
        ThreadPoolManager.getInstance().execute(clientPacket);
    }
}

From source file:sas.systems.imflux.network.udp.UdpControlPacketDecoder.java

License:Apache License

/**
 * Decodes a {@link DatagramPacket} to a {@link CompoundControlPacket} wrapped into an {@link AddressedEnvelope}.
 * //from  www  . j  av a2s . c  o  m
 * @param ctx The context of the ChannelHandler
 * @param message the message which should be encoded
 * @param out a list where all messages are written to
 */
@Override
protected void decode(ChannelHandlerContext ctx, DatagramPacket msg, List<Object> out) throws Exception {
    final ByteBuf content = msg.content();
    final SocketAddress sender = msg.sender();
    final SocketAddress recipient = msg.recipient();

    if ((content.readableBytes() % 4) != 0) {
        LOG.debug("Invalid RTCP packet received: total length should be multiple of 4 but is {}",
                content.readableBytes());
        return;
    }

    // Usually 2 packets per UDP frame...
    final List<ControlPacket> controlPacketList = new ArrayList<>(2);

    // While there's data to read, keep on decoding.
    while (content.readableBytes() > 0) {
        try {
            // prevent adding null
            final ControlPacket packet = ControlPacket.decode(content);
            if (packet != null) {
                controlPacketList.add(packet);
            }
        } catch (Exception e1) {
            LOG.debug("Exception caught while decoding RTCP packet.", e1);
            break;
        }
    }

    if (!controlPacketList.isEmpty()) {
        // Only forward to next ChannelHandler when there were more than one valid decoded packets.
        // TODO shouldn't the whole compound packet be discarded when one of them has errors?!
        final AddressedEnvelope<CompoundControlPacket, SocketAddress> newMsg = new DefaultAddressedEnvelope<>(
                new CompoundControlPacket(controlPacketList), recipient, sender);
        out.add(newMsg);
    }
}

From source file:sas.systems.imflux.network.udp.UdpDataPacketDecoder.java

License:Apache License

/**
 * Decodes a {@link DatagramPacket} to a {@link DataPacket} wrapped into an {@link AddressedEnvelope} to allow multicast on
 * the used {@link SocketChannel}. // ww  w  .  j  av a2s .co m
 * 
 * @param ctx The context of the ChannelHandler
 * @param message the message which should be encoded
 * @param out a list where all messages are written to
 */
@Override
protected void decode(ChannelHandlerContext ctx, DatagramPacket msg, List<Object> out) throws Exception {
    final ByteBuf content = msg.content();
    final SocketAddress sender = msg.sender();
    final SocketAddress recipient = msg.recipient();

    try {
        final DataPacket dataPacket = DataPacket.decode(content);
        final AddressedEnvelope<DataPacket, SocketAddress> newMsg = new DefaultAddressedEnvelope<DataPacket, SocketAddress>(
                dataPacket, recipient, sender);
        out.add(newMsg);
    } catch (Exception e) {
        LOG.debug("Failed to decode RTP packet.", e);
    }
}