Example usage for java.net DatagramPacket getLength

List of usage examples for java.net DatagramPacket getLength

Introduction

In this page you can find the example usage for java.net DatagramPacket getLength.

Prototype

public synchronized int getLength() 

Source Link

Document

Returns the length of the data to be sent or the length of the data received.

Usage

From source file:org.starnub.starnubserver.servers.starbound.UDPProxyServer.java

public void run() {
    InetAddress IPAddress;// w  w w . j  a va 2  s. com
    DatagramSocket ds;
    try {
        ds = new DatagramSocket(starnubPort);
        IPAddress = InetAddress.getByName(starboundAddress);
    } catch (SocketException | UnknownHostException e1) {
        StarNub.getLogger().cFatPrint("StarNub", ExceptionUtils.getMessage(e1));
        e1.printStackTrace();
        return;
    }

    byte[] request = new byte[1024];
    byte[] reply = new byte[4096];

    while (!stopping) {
        try {
            DatagramPacket from_client = new DatagramPacket(request, request.length);
            ds.receive(from_client);

            byte[] real_request = new byte[from_client.getLength()];
            System.arraycopy(request, 0, real_request, 0, from_client.getLength());

            DatagramPacket sendPacket = new DatagramPacket(real_request, real_request.length, IPAddress,
                    starboundPort);
            ds.send(sendPacket);

            DatagramPacket from_server = new DatagramPacket(reply, reply.length);
            ds.receive(from_server);
            byte[] real_reply = new byte[from_server.getLength()];
            System.arraycopy(reply, 0, real_reply, 0, from_server.getLength());

            InetAddress address = from_client.getAddress();
            int port = from_client.getPort();
            DatagramPacket to_client = new DatagramPacket(real_reply, real_reply.length, address, port);
            ds.send(to_client);
        } catch (Exception e) {
            StarNub.getLogger().cFatPrint("StarNub", ExceptionUtils.getMessage(e));
            return;
        }
    }
}

From source file:poisondog.net.udp.DatagramMission.java

public DatagramResponse execute(DatagramParameter parameter) throws IOException {
    DatagramSocket socket = new DatagramSocket(null);
    socket.setReuseAddress(true);/*from  w  w w . ja v a 2s.c  o  m*/

    socket.setBroadcast(parameter.getBroadcast());
    if (parameter.getTimeout() > 0)
        socket.setSoTimeout(parameter.getTimeout());
    String data = IOUtils.toString(parameter.getInputStream());
    DatagramPacket packet = new DatagramPacket(data.getBytes(), data.length());
    packet.setAddress(InetAddress.getByName(parameter.getHost()));
    packet.setPort(parameter.getPort());
    socket.send(packet);

    DatagramResponse response = new DatagramResponse(parameter.getResponseLength());
    DatagramPacket responsePacket = new DatagramPacket(response.getContent(), response.getContent().length);
    socket.receive(responsePacket);
    response.setAddress(responsePacket.getAddress().getHostAddress());
    response.setPacketLength(responsePacket.getLength());
    socket.close();
    return response;
}

From source file:org.apache.camel.component.mina.MinaUdpWithInOutUsingPlainSocketTest.java

private String sendAndReceiveUdpMessages(String input) throws Exception {
    DatagramSocket socket = new DatagramSocket();
    InetAddress address = InetAddress.getByName("127.0.0.1");

    byte[] data = input.getBytes();

    DatagramPacket packet = new DatagramPacket(data, data.length, address, PORT);
    LOG.debug("+++ Sending data +++");
    socket.send(packet);//from   w  ww  .  j a v a 2  s  .  c o  m

    Thread.sleep(1000);

    byte[] buf = new byte[128];
    DatagramPacket receive = new DatagramPacket(buf, buf.length, address, PORT);
    LOG.debug("+++ Receving data +++");
    socket.receive(receive);

    socket.close();

    return new String(receive.getData(), 0, receive.getLength());
}

From source file:org.apache.camel.component.netty.NettyUdpWithInOutUsingPlainSocketTest.java

private String sendAndReceiveUdpMessages(String input) throws Exception {
    DatagramSocket socket = new DatagramSocket();
    InetAddress address = InetAddress.getByName("127.0.0.1");

    // must append delimiter
    byte[] data = (input + "\n").getBytes();

    DatagramPacket packet = new DatagramPacket(data, data.length, address, PORT);
    LOG.debug("+++ Sending data +++");
    socket.send(packet);/*from ww w  .j  a v  a 2s.  c  o  m*/

    Thread.sleep(1000);

    byte[] buf = new byte[128];
    DatagramPacket receive = new DatagramPacket(buf, buf.length, address, PORT);
    LOG.debug("+++ Receiving data +++");
    socket.receive(receive);

    socket.close();

    return new String(receive.getData(), 0, receive.getLength());
}

From source file:com.bitbreeds.webrtc.dtls.DtlsMuxStunTransport.java

public int receive(byte[] buf, int off, int len, int waitMillis) throws IOException {
    socket.setSoTimeout(waitMillis);/*from   w ww .  j  a v a 2  s  . c  om*/
    DatagramPacket packet = new DatagramPacket(buf, off, len);
    socket.receive(packet);
    logger.trace("Socket read msg: {}",
            Hex.encodeHexString(SignalUtil.copyRange(buf, new ByteRange(0, packet.getLength()))));
    if (buf.length >= 2 && buf[0] == 0 && buf[1] == 1) {
        SocketAddress currentSender = packet.getSocketAddress();

        byte[] data = Arrays.copyOf(packet.getData(), packet.getLength());

        byte[] out = bindingService.processBindingRequest(data, parent.getLocal().getUserName(),
                parent.getLocal().getPassword(), (InetSocketAddress) currentSender);

        logger.trace("Stun packet received, responding with {}", Hex.encodeHexString(out));
        this.send(out, 0, out.length);
        return 0; //We do not want DTLS to process (not that it will anyway), so we return 0 here.
    }

    return packet.getLength();
}

From source file:org.nuxeo.runtime.detection.MulticastDetector.java

private String readHeartBeat(DatagramPacket p) {
    return new String(p.getData(), p.getOffset(), p.getLength());
}

From source file:org.apache.jcs.auxiliary.lateral.socket.udp.LateralUDPReceiver.java

/**
 * Highly unreliable. If it is processing one message while another comes in
 * , the second message is lost. This is for low concurency peppering.
 *//* w w  w. j a v a  2  s . c o m*/
public Object waitForMessage() throws IOException {
    final DatagramPacket packet = new DatagramPacket(m_buffer, m_buffer.length);

    Object obj = null;
    try {
        m_socket.receive(packet);

        final ByteArrayInputStream byteStream = new ByteArrayInputStream(m_buffer, 0, packet.getLength());

        final ObjectInputStream objectStream = new ObjectInputStream(byteStream);

        obj = objectStream.readObject();

    } catch (Exception e) {
        log.error(e);
        //throw new CacheException( "Error receving multicast packet", e);
    }
    return obj;
}

From source file:sx.blah.discord.api.internal.OpusPacket.java

OpusPacket(DatagramPacket udpPacket) {
    this.header = new RTPHeader(Arrays.copyOf(udpPacket.getData(), RTPHeader.LENGTH));
    this.audio = Arrays.copyOfRange(udpPacket.getData(), RTPHeader.LENGTH, udpPacket.getLength());
    this.isEncrypted = true;
}

From source file:fi.tut.fast.MulticastConsumer.java

private void consume() throws IOException {
    byte buf[] = new byte[endpoint.getMaxPacketSize()];
    DatagramPacket pack = new DatagramPacket(buf, buf.length);
    try {//w w w .j  a  v a  2  s. c o m
        s.receive(pack);
        try {
            messageQueue.add(new ExchangeDeliveryJob(pack.getData(), pack.getLength()));
        } catch (Exception e) {
            LOG.error("Exception Caught while processing UDP message.", e);
        }
    } catch (java.net.SocketTimeoutException ex) {
        // Timed out.. Listen again.
    }
}

From source file:org.openhab.binding.hue.internal.tools.SsdpDiscovery.java

/**
 * Checks whether a packet does contain all given keywords case insensitive.
 * If all keywords are contained the IP address of the packet sender will be
 * returned./*from  www  .  jav  a  2s  .c o m*/
 * 
 * @param packet
 *            The data packet to be analyzed.
 * @param keywords
 *            The keywords to be searched for.
 * @return The IP of the sender if all keywords have been found, null
 *         otherwise.
 * 
 * @throws IOException
 */
private String analyzePacket(DatagramPacket packet, String... keywords) throws IOException {

    logger.debug("Analyzing answer message.");

    InetAddress addr = packet.getAddress();
    ByteArrayInputStream in = new ByteArrayInputStream(packet.getData(), 0, packet.getLength());
    String response = IOUtils.toString(in);

    boolean foundAllKeywords = true;

    for (String keyword : keywords) {
        foundAllKeywords &= response.toUpperCase().contains(keyword.toUpperCase());
    }

    if (foundAllKeywords) {
        logger.debug("Found matching answer.");
        return addr.getHostAddress();
    }

    logger.debug("Answer did not match.");
    return null;
}