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.rhq.metrics.netty.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<Part>(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://from   ww  w.ja v a2s .com
            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;
    Part[] partsResult = collectdPacket.getParts();
    assertEquals("Wrong number of parts in the packet", numberOfParts, partsResult.length);

    for (int i = 0; i < partsResult.length; i++) {
        Part part = partsResult[i];
        assertEquals("Wrong packet order", parts.get(i).getPartType(), part.getPartType());
    }

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

From source file:org.rhq.metrics.netty.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;
    Part[] parts = collectdPacket.getParts();
    assertEquals("Expected only one part in the packet", 1, parts.length);

    Part part = parts[0];//from   w  w  w  .ja v a  2 s  . c om
    assertEquals(partClass, part.getClass());
    assertEquals(partType, part.getPartType());
    assertThat(part.getValue(), matcher);

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

From source file:org.rzo.netty.mcast.MulticastEndpoint.java

License:Apache License

public void send(ByteBuf msg) throws Exception {

    byte[] arr = msg.array();
    byte[] buf = new byte[arr.length + id.length];
    System.arraycopy(id, 0, buf, 0, id.length);
    System.arraycopy(arr, 0, buf, id.length, arr.length);

    ByteBuf bbuf = Unpooled.wrappedBuffer(buf);

    if (debug && logger != null)
        logger.info("discovery send " + new String(bbuf.array()));

    datagramChannel.writeAndFlush(new DatagramPacket(bbuf, multicastAddress)).sync();

    // datagramChannel.writeAndFlush(buf, multicastAddress);
}

From source file:qotm.QuoteOfTheMomentClient.java

License:Apache License

public static void main(String[] args) throws Exception {

    EventLoopGroup group = new NioEventLoopGroup();
    try {/*w  w w.  j a va  2  s  .  c  o  m*/
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true)
                .handler(new ChannelInitializer<NioDatagramChannel>() {
                    @Override
                    protected void initChannel(NioDatagramChannel ch) throws Exception {
                        //ch.pipeline().addLast(new UdpEncoder());
                        //ch.pipeline().addLast(new QuoteOfTheMomentClientHandler());

                    }
                });

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

        while (true) {
            // Broadcast the QOTM request to port 8080.
            ch.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer("QOTM?", CharsetUtil.UTF_8),
                    SocketUtils.socketAddress("192.168.0.23", 124))).sync();
            // Broadcast the QOTM request to port 8080.
            ch.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer("QOTM?", CharsetUtil.UTF_8),
                    SocketUtils.socketAddress("192.168.0.23", 123))).sync();
        }

        /*ch.writeAndFlush(new DatagramPacket(
            Unpooled.copiedBuffer("QOTM?", CharsetUtil.UTF_8),
            SocketUtils.socketAddress("192.168.0.23", 12345))).sync();*/

        // QuoteOfTheMomentClientHandler will close the DatagramChannel when a
        // response is received.  If the channel is not closed within 5 seconds,
        // print an error message and quit.
        /*if (!ch.closeFuture().await(5000)) {
        System.err.println("QOTM request timed out.");
        }*/
    } finally {
        group.shutdownGracefully();
    }
}

From source file:qotm.QuoteOfTheMomentServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
    System.err.println(packet);//from www  .  j  a va  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.Client.java

License:Apache License

public void sendPacket(Auth2ClientServerPacket packet) {
    packet.setClient(this);
    packet.write();//from   w ww  . j a v  a  2s.  c  o m

    ByteBuf buf = packet.getContent();
    buf = getPacketHandler().encrypt(buf);

    channel.writeAndFlush(new DatagramPacket(buf, myAddress));
}

From source file:ru.jts.gameserver.network.Client.java

License:Apache License

public void sendPacket(Game2ClientServerPacket packet) {
    packet.setClient(this);
    packet.write();/* ww  w . ja v  a 2 s  .  c  o m*/

    ByteBuf buf = packet.getContent();
    buf = getPacketHandler().encrypt(buf);

    channel.writeAndFlush(new DatagramPacket(buf, myAddress));
}

From source file:se.sics.gvod.net.NettyNetwork.java

License:Open Source License

/**
 * Send a message using UDP.//from  ww w . j  a  v  a  2 s.  c o  m
 *
 * @param msg the message to be sent
 * @throws ChannelException in case of connection problems
 */
private void sendUdp(RewriteableMsg msg) {
    InetSocketAddress src = address2SocketAddress(msg.getSource());
    InetSocketAddress dest = address2SocketAddress(msg.getDestination());

    if (src == null) {
        String strError = "Source for msg " + "of type " + msg.getClass()
                + " is not bound at network component: " + msg.getSource();
        logger.error(strError);
        //            throw new IllegalArgumentException(strError);
        return;
    }

    // use one channel per local socket
    // session-less UDP. This means that remoteAddresses cannot be found in
    // the channel object, but only in the MessageEvent object.
    //        DatagramChannel channel = udpSocketsToChannels.get(src);
    DatagramChannel channel = udpSocketsToChannels.get(src.getPort());
    if (channel == null) {
        String strError = "Source for msg " + "of type " + msg.getClass()
                + " . Port not bound at client, need to bind the port first: " + msg.getSource();
        logger.error(strError);
        //            throw new IllegalArgumentException(strError);
        return;
    }
    try {
        logger.trace("Sending " + msg.getClass().getCanonicalName() + " from {} to {} ", msg.getSource(),
                msg.getDestination());
        channel.writeAndFlush(new DatagramPacket(((Encodable) msg).toByteArray(), dest));
        totalWrittenBytes += msg.getSize();
    } catch (Exception ex) {
        ex.printStackTrace();
        logger.warn("Problem trying to send msg of type: " + msg.getClass().getCanonicalName()
                + " with src address: " + src.toString() + " and dest address: " + msg.getDestination()
                + " Exception: " + ex.getMessage() + " " + ex.getClass());
        if (BaseCommandLineConfig.reportNettyExceptions()) {
            try {
                NatReportMsg.NatReport nr = new NatReportMsg.NatReport(msg.getSource().getPort(),
                        ToVodAddr.systemAddr(msg.getDestination()), false, 0,
                        "Netty error: " + ex.getMessage());
                List<NatReportMsg.NatReport> nrs = new ArrayList<NatReportMsg.NatReport>();
                nrs.add(nr);
                VodAddress reportServer = ToVodAddr.bootstrap(VodConfig.getBootstrapServer());
                NatReportMsg evt = new NatReportMsg(ToVodAddr.systemAddr(msg.getSource()), reportServer, nrs);
                InetSocketAddress reportDest = address2SocketAddress(reportServer.getPeerAddress());
                channel.writeAndFlush(new DatagramPacket(((Encodable) evt).toByteArray(), reportDest));
            } catch (Throwable t) {
                logger.warn("Couldn't report exception to NatReportServer: " + t.getMessage());
            }
        }
    }
}

From source file:se.sics.kompics.network.netty.NettyNetwork.java

License:Open Source License

private ChannelFuture sendUdpMessage(Msg message) {
    InetSocketAddress src = addressToSocket(message.getSource());
    InetSocketAddress dst = addressToSocket(message.getDestination());
    Channel c = udpChannels.get(src);
    //ByteBuf buf = Unpooled.buffer(INITIAL_BUFFER_SIZE, SEND_BUFFER_SIZE);
    ByteBuf buf = c.alloc().buffer(INITIAL_BUFFER_SIZE, SEND_BUFFER_SIZE);
    try {//  w  w w.jav  a  2  s  .  c o m
        Serializers.toBinary(message, buf);
        DatagramPacket pack = new DatagramPacket(buf, dst);
        LOG.debug("Sending Datagram message {} from {} to {}", new Object[] { message, src, dst });
        return c.writeAndFlush(pack);
    } catch (Exception e) { // serialization might fail horribly with size bounded buff
        LOG.warn("Could not send Datagram message {}, error was: {}", message, e);
        return null;
    }
}