Example usage for java.net DatagramPacket getData

List of usage examples for java.net DatagramPacket getData

Introduction

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

Prototype

public synchronized byte[] getData() 

Source Link

Document

Returns the data buffer.

Usage

From source file:org.restcomm.sbc.media.MediaZone.java

public void send(DatagramPacket dgram) throws IOException {

    if (dgram == null)
        return;//from   w ww . j  a va2  s.c o m

    dgram.setAddress(mediaZonePeer.getOriginalAddress());
    dgram.setPort(mediaZonePeer.getOriginalRtpPort());
    //dgram.setData(mediaZonePeer.encodeRTP(dgram.getData(), 0, dgram.getLength()), 0, dgram.getLength() );   
    //LOG.trace("--->("+this.mediaType+", "+this.direction+") LocalProxy "+proxyHost+":"+proxyPort+"/"+dgram.getAddress()+":"+dgram.getPort()+"["+dgram.getLength()+"]");   
    //LOG.trace("---> via socket "+toPrint(socket));   
    if (dgram.getData().length > 8) {
        if (logCounter == rtpCountLog) {
            RawPacket rtp = new RawPacket(dgram.getData(), 0, dgram.getLength());
            LOG.trace("--->[PayloadType " + rtp.getPayloadType() + "](" + this.mediaType + ", " + this.direction
                    + ") LocalProxy " + proxyHost + ":" + proxyPort + "/" + dgram.getAddress() + ":"
                    + dgram.getPort() + "[" + dgram.getLength() + "]");
            logCounter = 0;
        }
    } else {
        LOG.warn("--->[PayloadType ?](" + this.mediaType + ", " + this.direction + ") LocalProxy " + proxyHost
                + ":" + proxyPort + "/" + dgram.getAddress() + ":" + dgram.getPort() + "[" + dgram.getLength()
                + "]");
    }

    packetsSentCounter++;

    socket.send(dgram);

}

From source file:ws.argo.Responder.Responder.java

public void run() throws IOException, ClassNotFoundException {

    ArrayList<ProbeHandlerPluginIntf> handlers = new ArrayList<ProbeHandlerPluginIntf>();

    // load up the handler classes specified in the configuration parameters
    // I hope the hander classes are in a jar file on the classpath
    handlers = loadHandlerPlugins(cliValues.config.appHandlerConfigs);

    @SuppressWarnings("resource")
    MulticastSocket socket = new MulticastSocket(cliValues.config.multicastPort);
    address = InetAddress.getByName(cliValues.config.multicastAddress);
    LOGGER.info("Starting Responder on " + address.toString() + ":" + cliValues.config.multicastPort);
    socket.joinGroup(address);/*from  ww  w.  java  2  s .  c om*/

    DatagramPacket packet;
    ResponsePayloadBean response = null;

    LOGGER.info(
            "Responder started on " + cliValues.config.multicastAddress + ":" + cliValues.config.multicastPort);

    httpClient = HttpClients.createDefault();

    LOGGER.fine("Starting Responder loop - infinite until process terminated");
    // infinite loop until the responder is terminated
    while (true) {

        byte[] buf = new byte[1024];
        packet = new DatagramPacket(buf, buf.length);
        LOGGER.fine("Waiting to recieve packet...");
        socket.receive(packet);

        LOGGER.fine("Received packet");
        LOGGER.fine("Packet contents:");
        // Get the string
        String probeStr = new String(packet.getData(), 0, packet.getLength());
        LOGGER.fine("Probe: \n" + probeStr);

        try {
            ProbePayloadBean payload = parseProbePayload(probeStr);

            LOGGER.info("Received probe id: " + payload.probeID);

            // Only handle probes that we haven't handled before
            // The Probe Generator needs to send a stream of identical UDP packets
            // to compensate for UDP reliability issues.  Therefore, the Responder
            // will likely get more than 1 identical probe.  We should ignore duplicates.
            if (!handledProbes.contains(payload.probeID)) {
                for (ProbeHandlerPluginIntf handler : handlers) {
                    response = handler.probeEvent(payload);
                    sendResponse(payload.respondToURL, payload.respondToPayloadType, response);
                }
                handledProbes.add(payload.probeID);
            } else {
                LOGGER.info("Discarding duplicate probe with id: " + payload.probeID);
            }

        } catch (SAXException e) {
            // TODO Auto-generated catch block

            e.printStackTrace();
        }

    }

}

From source file:nl.mindef.c2sc.nbs.olsr.pud.uplink.server.handlers.impl.PacketHandlerImpl.java

@Override
@Transactional/*from   w  w  w.  ja v a 2  s  .c o  m*/
public boolean processPacket(RelayServer relayServer, DatagramPacket packet) {
    try {
        this.txChecker.checkInTx("PacketHandler::processPacket");
    } catch (Throwable e) {
        e.printStackTrace();
    }

    long utcTimestamp = System.currentTimeMillis();
    boolean updated = false;

    if (this.logger.isDebugEnabled()) {
        this.logger.debug("[" + utcTimestamp + "] Received " + packet.getLength() + " bytes from "
                + packet.getAddress().getHostAddress() + ":" + packet.getPort());
    }

    try {
        InetAddress srcIp = packet.getAddress();
        int srcPort = packet.getPort();

        /* get sender or create */
        Sender sender = this.senders.getSender(srcIp, srcPort);
        if (sender == null) {
            sender = new Sender(srcIp, Integer.valueOf(srcPort), relayServer);
        }

        /* make sure the sender is linked to this relayServer */
        sender.setRelayServer(relayServer);

        /* get packet data */
        byte[] packetData = packet.getData();
        int packetLength = packet.getLength();

        /* parse the uplink packet for messages */
        int messageOffset = 0;
        while (messageOffset < packetLength) {
            int messageType = UplinkMessage.getUplinkMessageType(packetData, messageOffset);
            int messageLength = UplinkMessage.getUplinkMessageHeaderLength()
                    + UplinkMessage.getUplinkMessageLength(packetData, messageOffset);

            if ((messageType != UplinkMessage.getUplinkMessageTypePosition())
                    && (messageType != UplinkMessage.getUplinkMessageTypeClusterLeader())) {
                this.logger.warn("Uplink message type " + messageType + " not supported: ignored");
            } else {
                byte[] messageData = Arrays.copyOfRange(packetData, messageOffset,
                        messageOffset + messageLength);
                DumpUtil.dumpUplinkMessage(this.logger, Level.DEBUG, messageData, srcIp, srcPort, messageType,
                        utcTimestamp, "  ");

                Object msg = null;
                boolean msgCausedUpdate = false;
                if (messageType == UplinkMessage.getUplinkMessageTypePosition()) {
                    msg = new PositionUpdate(messageData, messageLength);
                    msgCausedUpdate = this.positionUpdateHandler.handlePositionMessage(sender, utcTimestamp,
                            (PositionUpdate) msg);
                } else /* if (messageType == UplinkMessage.getUplinkMessageTypeClusterLeader()) */ {
                    msg = new ClusterLeader(messageData, messageLength);
                    msgCausedUpdate = this.clusterLeaderHandler.handleClusterLeaderMessage(sender, utcTimestamp,
                            (ClusterLeader) msg);
                }
                if (msgCausedUpdate && this.useFaker) {
                    this.faker.fakeit(sender, utcTimestamp, msg);
                }
                updated = msgCausedUpdate || updated;
            }

            messageOffset += messageLength;
        }

        return updated;
    } catch (Throwable e) {
        this.logger.error("error during packet handling", e);
        return updated;
    } finally {
        if (this.useFaker) {
            this.faker.setFirstFake(false);
        }
    }
}

From source file:org.lockss.test.LockssTestCase.java

/**
 * Asserts that the two DatagramPackets have equal contents
 * @param expected the expected value//from w ww . j av a 2  s .c om
 * @param actual the actual value
 */
public static void assertEquals(DatagramPacket expected, DatagramPacket actual) {
    assertEquals(expected.getAddress(), actual.getAddress());
    assertEquals(expected.getPort(), actual.getPort());
    assertEquals(expected.getLength(), actual.getLength());
    assertEquals(expected.getOffset(), actual.getOffset());
    assertTrue(Arrays.equals(expected.getData(), actual.getData()));
}

From source file:QuoteServerThread.java

void doIt(int port) {
        DatagramPacket packet;
        byte[] sendBuf = new byte[256];

        packet = new DatagramPacket(sendBuf, 256, address, port);

        try { // send request
            if (DEBUG) {
                System.out.println("Applet about to send packet to address " + address + " at port " + port);
            }/*from www.  jav  a2s.  co  m*/
            socket.send(packet);
            if (DEBUG) {
                System.out.println("Applet sent packet.");
            }
        } catch (IOException e) {
            System.out.println("Applet socket.send failed:");
            e.printStackTrace();
            return;
        }

        packet = new DatagramPacket(sendBuf, 256);

        try { // get response
            if (DEBUG) {
                System.out.println("Applet about to call socket.receive().");
            }
            socket.receive(packet);
            if (DEBUG) {
                System.out.println("Applet returned from socket.receive().");
            }
        } catch (IOException e) {
            System.out.println("Applet socket.receive failed:");
            e.printStackTrace();
            return;
        }

        String received = new String(packet.getData());
        if (DEBUG) {
            System.out.println("Quote of the Moment: " + received);
        }
        display.setText(received);
    }

From source file:org.openhab.io.hueemulation.internal.HueEmulationUpnpServer.java

@Override
public void run() {
    MulticastSocket recvSocket = null;
    // since jupnp shares port 1900, lets use a different port to send UDP packets on just to be safe.
    DatagramSocket sendSocket = null;
    byte[] buf = new byte[1000];
    DatagramPacket recv = new DatagramPacket(buf, buf.length);
    while (running) {
        try {//from w w w.j a va  2 s  . c om
            if (discoveryIp != null && discoveryIp.trim().length() > 0) {
                address = InetAddress.getByName(discoveryIp);
            } else {
                Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
                while (interfaces.hasMoreElements()) {
                    NetworkInterface ni = interfaces.nextElement();
                    Enumeration<InetAddress> addresses = ni.getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        InetAddress addr = addresses.nextElement();
                        if (addr instanceof Inet4Address && !addr.isLoopbackAddress()) {
                            address = addr;
                            break;
                        }
                    }
                }
            }
            InetSocketAddress socketAddr = new InetSocketAddress(MULTI_ADDR, UPNP_PORT_RECV);
            recvSocket = new MulticastSocket(UPNP_PORT_RECV);
            recvSocket.joinGroup(socketAddr, NetworkInterface.getByInetAddress(address));
            sendSocket = new DatagramSocket();
            while (running) {
                recvSocket.receive(recv);
                if (recv.getLength() > 0) {
                    String data = new String(recv.getData());
                    logger.trace("Got SSDP Discovery packet from {}:{}", recv.getAddress().getHostAddress(),
                            recv.getPort());
                    if (data.startsWith("M-SEARCH")) {
                        String msg = String.format(discoString, "http://" + address.getHostAddress().toString()
                                + ":" + System.getProperty("org.osgi.service.http.port") + discoPath, usn);
                        DatagramPacket response = new DatagramPacket(msg.getBytes(), msg.length(),
                                recv.getAddress(), recv.getPort());
                        try {
                            logger.trace("Sending to {} : {}", recv.getAddress().getHostAddress(), msg);
                            sendSocket.send(response);
                        } catch (IOException e) {
                            logger.error("Could not send UPNP response", e);
                        }
                    }
                }
            }
        } catch (SocketException e) {
            logger.error("Socket error with UPNP server", e);
        } catch (IOException e) {
            logger.error("IO Error with UPNP server", e);
        } finally {
            IOUtils.closeQuietly(recvSocket);
            IOUtils.closeQuietly(sendSocket);
            if (running) {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                }
            }
        }
    }
}

From source file:snapshotTools.java

private String callOvnmanager(String node, String action) {
    String result = "";
    DatagramSocket socket = null;
    int serverPort = 9999;
    DatagramPacket packet2Send;/*from  w  ww .jav a2 s .c  o m*/
    DatagramPacket receivedPacket;
    InetAddress theServerAddress;
    byte[] outBuffer;
    byte[] inBuffer;
    inBuffer = new byte[8192];
    outBuffer = new byte[8192];
    try {
        HttpSession session = RuntimeAccess.getInstance().getSession();
        String sessionUser = (String) session.getAttribute("User");
        if (sessionUser == null) {
            sessionUser = "administrator";
        }
        JSONObject joCmd = new JSONObject();
        JSONObject joAction = new JSONObject(action);
        joCmd.put("sender", sessionUser);
        joCmd.put("target", "SNAPSHOT");
        joCmd.put("node", node);
        joCmd.put("action", joAction);
        String output = joCmd.toString();

        socket = new DatagramSocket();
        String actionName = joAction.get("name").toString();
        if (actionName.equals("create")) {
            socket.setSoTimeout(180000);
        } else {
            socket.setSoTimeout(60000);
        }

        InetAddress serverInet = InetAddress.getByName("localhost");
        socket.connect(serverInet, serverPort);
        outBuffer = output.getBytes();
        packet2Send = new DatagramPacket(outBuffer, outBuffer.length, serverInet, serverPort);

        try {
            // send the data
            socket.send(packet2Send);
            receivedPacket = new DatagramPacket(inBuffer, inBuffer.length);
            socket.receive(receivedPacket);
            // the server response is...
            result = new String(receivedPacket.getData(), 0, receivedPacket.getLength());
            session.setAttribute("LastActive", System.currentTimeMillis());
        } catch (Exception excep) {
            String msg = excep.getMessage();
            //String msg = excep.toString();
            joCmd.remove("action");
            joAction.put("result", "Error:" + msg);
            joCmd.put("action", joAction);
            result = joCmd.toString();
        }
        socket.close();

    } catch (Exception e) {
        log(ERROR, "callOvnmanager", e);
        return e.toString();
    }
    return result;
}

From source file:org.springframework.integration.ip.udp.DatagramPacketSendingHandlerTests.java

@Test
public void verifySendWithAck() throws Exception {

    final List<Integer> openPorts = SocketUtils.findAvailableUdpSockets(SocketUtils.getRandomSeedPort(), 2);

    final int testPort = openPorts.get(0);
    final int ackPort = openPorts.get(1);

    byte[] buffer = new byte[1000];
    final DatagramPacket receivedPacket = new DatagramPacket(buffer, buffer.length);
    final CountDownLatch latch1 = new CountDownLatch(1);
    final CountDownLatch latch2 = new CountDownLatch(1);
    UnicastSendingMessageHandler handler = new UnicastSendingMessageHandler("localhost", testPort, true, true,
            "localhost", ackPort, 5000);
    handler.afterPropertiesSet();//from  w w w  .  jav a 2s .  co m
    Executors.newSingleThreadExecutor().execute(new Runnable() {
        public void run() {
            try {
                DatagramSocket socket = new DatagramSocket(testPort);
                latch1.countDown();
                socket.receive(receivedPacket);
                socket.close();
                DatagramPacketMessageMapper mapper = new DatagramPacketMessageMapper();
                mapper.setAcknowledge(true);
                mapper.setLengthCheck(true);
                Message<byte[]> message = mapper.toMessage(receivedPacket);
                Object id = message.getHeaders().get(IpHeaders.ACK_ID);
                byte[] ack = id.toString().getBytes();
                DatagramPacket ackPack = new DatagramPacket(ack, ack.length,
                        new InetSocketAddress("localHost", ackPort));
                DatagramSocket out = new DatagramSocket();
                out.send(ackPack);
                out.close();
                latch2.countDown();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    latch1.await(3000, TimeUnit.MILLISECONDS);
    String payload = "foobar";
    handler.handleMessage(MessageBuilder.withPayload(payload).build());
    assertTrue(latch2.await(10000, TimeUnit.MILLISECONDS));
    byte[] src = receivedPacket.getData();
    int length = receivedPacket.getLength();
    int offset = receivedPacket.getOffset();
    byte[] dest = new byte[6];
    System.arraycopy(src, offset + length - 6, dest, 0, 6);
    assertEquals(payload, new String(dest));
    handler.shutDown();
}

From source file:vmXmlFile.java

private String callOvnmanager(String node, String action) {
    String result = "";
    DatagramSocket socket = null;
    int serverPort = 9999;
    DatagramPacket packet2Send;/*from   ww  w .  j a v  a 2  s.co m*/
    DatagramPacket receivedPacket;
    InetAddress theServerAddress;
    byte[] outBuffer;
    byte[] inBuffer;
    inBuffer = new byte[65536];
    outBuffer = new byte[8192];

    try {
        HttpSession session = RuntimeAccess.getInstance().getSession();
        String sessionUser = (String) session.getAttribute("User");
        if (sessionUser == null) {
            sessionUser = "administrator";
        }
        JSONObject joCmd = new JSONObject();
        JSONObject joAction = new JSONObject(action);
        joCmd.put("sender", sessionUser);
        joCmd.put("target", "VM");
        joCmd.put("node", node);
        joCmd.put("action", joAction);
        String output = joCmd.toString();

        socket = new DatagramSocket();
        InetAddress serverInet = InetAddress.getByName("localhost");
        socket.connect(serverInet, serverPort);
        outBuffer = output.getBytes();
        packet2Send = new DatagramPacket(outBuffer, outBuffer.length, serverInet, serverPort);
        // send the data
        socket.send(packet2Send);

        receivedPacket = new DatagramPacket(inBuffer, inBuffer.length);
        socket.receive(receivedPacket);

        // the server response is...
        result = new String(receivedPacket.getData(), 0, receivedPacket.getLength());
        session.setAttribute("LastActive", System.currentTimeMillis());
        socket.close();

    } catch (Exception e) {
        log(ERROR, "callOvnmanager", e);
        return e.toString();
    }
    return result;
}