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:com.whirvis.jraknet.peer.RakNetPeer.java

License:Open Source License

/**
 * Sends a message over the channel raw.
 * <p>/* w  w  w  .  j av  a 2 s  .  c  o m*/
 * This will automatically update the <code>lastPacketSendTime</code> and
 * <code>packetsSentThisSecond</code> variable.
 * 
 * @param buf
 *            the buffer.
 * @throws NullPointerException
 *             if the <code>buf</code> is <code>null</code>.
 */
public final void sendNettyMessage(ByteBuf buf) throws NullPointerException {
    if (buf == null) {
        throw new NullPointerException("Buffer cannot be null");
    }
    channel.writeAndFlush(new DatagramPacket(buf, address));
    long currentTime = System.currentTimeMillis();
    if (currentTime - lastPacketsSentThisSecondResetTime >= 1000L) {
        this.packetsSentThisSecond = 0;
        this.lastPacketsSentThisSecondResetTime = currentTime;
    }
    this.lastPacketSendTime = currentTime;
    this.packetsSentThisSecond++;
    log.debug("Sent netty message with size of " + buf.capacity() + " bytes (" + (buf.capacity() * 8)
            + " bits) to " + address);
}

From source file:com.whirvis.jraknet.RakNet.java

License:Open Source License

/**
 * Sends a packet to the specified address.
 * //from   w  ww.  j a v  a  2s  . c  o  m
 * @param address
 *            the address to send the packet to.
 * @param packet
 *            the packet to send.
 * @param timeout
 *            how long to wait until resending the packet.
 * @param retries
 *            how many times the packet will be sent before giving up.
 * @return the packet received in response, <code>null</code> if no response
 *         was received or the thread was interrupted.
 * @throws NullPointerException
 *             if the <code>address</code>, IP address of the
 *             <code>address</code>, or <code>packet</code> are
 *             <code>null</code>.
 * @throws IllegalArgumentException
 *             if the <code>timeout</code> or <code>retries</code> are less
 *             than or equal to <code>0</code>.
 */
private static RakNetPacket createBootstrapAndSend(InetSocketAddress address, Packet packet, long timeout,
        int retries) throws NullPointerException, IllegalArgumentException {
    if (address == null) {
        throw new NullPointerException("Address cannot be null");
    } else if (address.getAddress() == null) {
        throw new NullPointerException("IP address cannot be null");
    } else if (packet == null) {
        throw new NullPointerException("Packet cannot be null");
    } else if (timeout <= 0) {
        throw new IllegalArgumentException("Timeout must be greater than 0");
    } else if (retries <= 0) {
        throw new IllegalArgumentException("Retriest must be greater than 0");
    }

    // Prepare bootstrap
    RakNetPacket received = null;
    EventLoopGroup group = new NioEventLoopGroup();
    int maximumTransferUnit = getMaximumTransferUnit();
    if (maximumTransferUnit < MINIMUM_MTU_SIZE) {
        return null;
    }
    try {
        // Create bootstrap
        Bootstrap bootstrap = new Bootstrap();
        BootstrapHandler handler = new BootstrapHandler();
        bootstrap.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true)
                .option(ChannelOption.SO_RCVBUF, maximumTransferUnit)
                .option(ChannelOption.SO_SNDBUF, maximumTransferUnit).handler(handler);
        Channel channel = bootstrap.bind(0).sync().channel();

        // Wait for response
        while (retries > 0 && received == null && !Thread.currentThread().isInterrupted()) {
            long sendTime = System.currentTimeMillis();
            channel.writeAndFlush(new DatagramPacket(packet.buffer(), address));
            while (System.currentTimeMillis() - sendTime < timeout && handler.packet == null)
                ; // Wait for either a timeout or a response
            received = handler.packet;
            retries--;
        }
    } catch (InterruptedException e) {
        return null;
    }
    group.shutdownGracefully();
    return received;
}

From source file:com.whizzosoftware.foscam.camera.discovery.FoscamCameraDiscovery.java

License:Open Source License

/**
 * Send a new search request./*from ww w  . ja  v  a  2 s . c  o m*/
 */
public void sendSearchRequest() {
    SearchRequest searchReq = new SearchRequest();
    logger.debug("Sending search request");
    channel.writeAndFlush(
            new DatagramPacket(searchReq.toByteBuf(), new InetSocketAddress("255.255.255.255", 10000)));
}

From source file:com.whizzosoftware.hobson.lifx.api.codec.LIFXFrameDecoderTest.java

License:Open Source License

@Test
public void testLightState() throws Exception {
    byte[] expected = new byte[] { 0x58, 0x00, 0x00, 0x54, 0x42, 0x52, 0x4B, 0x52, (byte) 0xD0, 0x73,
            (byte) 0xD5, 0x12, 0x09, 0x34, 0x00, 0x00, 0x4C, 0x49, 0x46, 0x58, 0x56, 0x32, 0x00, 0x00, 0x58,
            (byte) 0x92, 0x17, (byte) 0xD9, 0x2E, 0x0F, 0x3C, 0x14, 0x6B, 0x00, 0x00, 0x00, (byte) 0xD3,
            (byte) 0xFD, 0x00, 0x00, (byte) 0xFF, (byte) 0xFF, (byte) 0xAC, 0x0D, 0x00, 0x00, (byte) 0xFF,
            (byte) 0xFF, 0x44, 0x61, 0x6E, 0x27, 0x73, 0x20, 0x4F, 0x66, 0x66, 0x69, 0x63, 0x65, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
    LIFXFrameDecoder d = new LIFXFrameDecoder();
    List<Object> list = new ArrayList<>();
    d.decode(null, new DatagramPacket(Unpooled.wrappedBuffer(expected),
            new InetSocketAddress("255.255.255.255", 56700)), list);
    assertEquals(1, list.size());//from  w w w  .j a v  a2s .com
    assertTrue(list.get(0) instanceof LightState);
    assertEquals("Dan's Office", ((LightState) list.get(0)).getLabel());
}

From source file:com.whizzosoftware.hobson.lifx.api.codec.LIFXFrameEncoder.java

License:Open Source License

@Override
protected void encode(ChannelHandlerContext channelHandlerContext, Message m, List<Object> list)
        throws Exception {
    ByteBuf buf = null;/*w w w .j a va 2 s  .c o  m*/

    switch (m.getType()) {
    case DeviceGetPower.TYPE:
    case DeviceGetService.TYPE:
    case LightGet.TYPE:
        buf = Unpooled.buffer(m.getLength());
        writeMessageHeader(buf, m.getHeader());
        break;
    case DeviceSetPower.TYPE:
        buf = Unpooled.buffer(m.getLength());
        writeDeviceSetPower(buf, (DeviceSetPower) m);
        break;
    case LightSetColor.TYPE:
        buf = Unpooled.buffer(m.getLength());
        writeLightSetColor(buf, (LightSetColor) m);
        break;
    case LightSetPower.TYPE:
        buf = Unpooled.buffer(m.getLength());
        writeLightSetPower(buf, (LightSetPower) m);
        break;
    default:
        logger.error("Unsupported message passed to encoder: {}", m);
    }

    if (buf != null) {
        list.add(new DatagramPacket(buf, m.getRecipient()));
    } else {
        logger.error("Unknown message passed to encoder: {}", m);
    }
}

From source file:com.zhaopeng.timeserver.protocol.udp.ChineseProverbServerHandler.java

License:Apache License

public void messageReceived(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
    String req = packet.content().toString(CharsetUtil.UTF_8);
    System.out.println(req);//from  w  w w .  jav a  2  s .c o  m
    if ("?".equals(req)) {
        ctx.writeAndFlush(new DatagramPacket(
                Unpooled.copiedBuffer(": " + nextQuote(), CharsetUtil.UTF_8),
                packet.sender()));
    }
}

From source file:de.jackwhite20.apex.udp.pipeline.DatagramDownstreamHandler.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket datagramPacket) throws Exception {

    if (channel.isActive()) {
        channel.writeAndFlush(new DatagramPacket(datagramPacket.content().retain(), sender));
    }//from  www. j av  a 2 s. c o  m
}

From source file:de.jackwhite20.apex.udp.pipeline.DatagramUpstreamHandler.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket datagramPacket) throws Exception {

    BackendInfo backendInfo = ApexDatagram.getBalancingStrategy().selectBackend("", 0);

    if (backendInfo == null) {
        logger.error("Unable to select a backend server. All down?");
        return;/*from   w ww.jav a2 s. c o m*/
    }

    // Only copy if there is at least one backend server
    ByteBuf copy = datagramPacket.content().copy().retain();

    Bootstrap bootstrap = new Bootstrap().channel(PipelineUtils.getDatagramChannel())
            .handler(new DatagramDownstreamHandler(ctx.channel(), datagramPacket.sender()))
            .group(ctx.channel().eventLoop());

    ChannelFuture channelFuture = bootstrap.bind(0);

    // Add the traffic shaping handler to the channel pipeline
    GlobalTrafficShapingHandler trafficShapingHandler = Apex.getInstance().getTrafficShapingHandler();
    if (trafficShapingHandler != null) {
        // The handler needs to be the first handler in the pipeline
        channelFuture.channel().pipeline().addFirst(trafficShapingHandler);
    }

    channelFuture.addListener((ChannelFutureListener) channelFuture1 -> {

        Channel channel = channelFuture1.channel();
        if (channelFuture1.isSuccess()) {
            channel.writeAndFlush(new DatagramPacket(copy,
                    new InetSocketAddress(backendInfo.getHost(), backendInfo.getPort())));
        } else {
            ChannelUtil.close(channel);
        }

        // Release the buffer
        copy.release();
    });

    // Keep track of request per second
    if (connectionsPerSecondTask != null) {
        connectionsPerSecondTask.inc();
    }
}

From source file:de.unipassau.isl.evs.ssh.core.network.UDPDiscoveryClient.java

License:Open Source License

/**
 * Send a single UDP discovery request. It contains of {@link CoreConstants.NettyConstants#DISCOVERY_PAYLOAD_REQUEST}
 * as header followed by the Public Key of the sought-after Master.
 * Both byte arrays are prefixed by their length as int.
 *
 * @return the ChannelFuture returned by {@link io.netty.channel.Channel#write(Object)}
 *//*from  ww w .ja  v a 2s .  c o m*/
private ChannelFuture sendDiscoveryRequest() {
    final NamingManager namingManager = requireComponent(NamingManager.KEY);
    if (namingManager.isMasterIDKnown()) {
        Log.v(TAG, "sendDiscoveryRequest looking for Master " + namingManager.getMasterID());
    } else {
        Log.v(TAG, "sendDiscoveryRequest looking for any Master");
    }

    final byte[] header = DISCOVERY_PAYLOAD_REQUEST.getBytes();
    final byte[] ownIDBytes = namingManager.getOwnID().getIDBytes();
    final ByteBuf buffer = channel.channel().alloc().buffer();
    buffer.writeInt(header.length);
    buffer.writeBytes(header);
    buffer.writeInt(ownIDBytes.length);
    buffer.writeBytes(ownIDBytes);

    if (namingManager.isMasterIDKnown()) {
        buffer.writeBoolean(true);
        final byte[] masterIDBytes = namingManager.getMasterID().getIDBytes();
        buffer.writeInt(masterIDBytes.length);
        buffer.writeBytes(masterIDBytes);
    } else {
        buffer.writeBoolean(false);
    }

    final InetSocketAddress recipient = new InetSocketAddress(DISCOVERY_HOST, DISCOVERY_SERVER_PORT);
    final DatagramPacket request = new DatagramPacket(buffer, recipient);
    return channel.channel().writeAndFlush(request);
}

From source file:de.unipassau.isl.evs.ssh.master.network.UDPDiscoveryServer.java

License:Open Source License

/**
 * Send a response with the ConnectInformation of this Master to the requesting Client.
 *
 * @param request the request sent from a {@link Client}
 *//*from w w  w. jav a2  s.  c  o  m*/
private void sendDiscoveryResponse(DatagramPacket request) {
    final ByteBuf buffer = channel.channel().alloc().heapBuffer();

    // gather information
    final byte[] header = DISCOVERY_PAYLOAD_RESPONSE.getBytes();
    final String addressString = request.recipient().getAddress().getHostAddress();
    final byte[] address = addressString.getBytes();
    final InetSocketAddress serverAddress = requireComponent(Server.KEY).getAddress();
    if (serverAddress == null) {
        Log.w(TAG, "Could not respond to UDP discovery request as Server is not started yet");
        return;
    }
    final int port = serverAddress.getPort();
    Log.i(TAG, "sendDiscoveryResponse with connection data " + addressString + ":" + port + " to "
            + request.sender());

    // write it to the buffer
    buffer.writeInt(header.length);
    buffer.writeBytes(header);
    buffer.writeInt(address.length);
    buffer.writeBytes(address);
    buffer.writeInt(port);

    // and sign the data
    try {
        Signature signature = Signature.getInstance("ECDSA");
        signature.initSign(requireComponent(KeyStoreController.KEY).getOwnPrivateKey());
        signature.update(buffer.nioBuffer());
        final byte[] sign = signature.sign();
        buffer.writeInt(sign.length);
        buffer.writeBytes(sign);
    } catch (GeneralSecurityException e) {
        Log.w(TAG, "Could not send UDP discovery response", e);
    }

    final DatagramPacket response = new DatagramPacket(buffer, request.sender());
    channel.channel().writeAndFlush(response);
}