Example usage for java.net DatagramSocket receive

List of usage examples for java.net DatagramSocket receive

Introduction

In this page you can find the example usage for java.net DatagramSocket receive.

Prototype

public synchronized void receive(DatagramPacket p) throws IOException 

Source Link

Document

Receives a datagram packet from this socket.

Usage

From source file:com.mobilyzer.measurements.RRCTask.java

/**
 * Sends a bunch of UDP packets of the size indicated and wait for the response.
 * /* w  ww  . j  ava 2s  .co m*/
 * Counts how long it takes for all the packets to return. PAckets are currently not labelled: the
 * total time is the time for the first packet to leave until the last packet arrives. AFter 7000
 * ms it is assumed packets are lost and the socket times out. In that case, the number of packets
 * lost is recorded.
 * 
 * @param serverAddr server to which to send the packets
 * @param size size of the packets
 * @param num number of packets to send
 * @param packetSize size of the packets sent
 * @param port port to send the packets to
 * @return first value: the amount of time to send all packets and get a response. second value:
 *         number of packets lost, on a timeout.
 * @throws IOException
 */
public static long[] sendMultiPackets(InetAddress serverAddr, int size, int num, int packetSize, int port)
        throws IOException {

    long startTime = 0;
    long endTime = 0;
    byte[] buf = new byte[size];
    byte[] rcvBuf = new byte[packetSize];
    long[] retval = { -1, -1 };
    long numLost = 0;
    int i = 0;

    DatagramSocket socket = new DatagramSocket();
    DatagramPacket packetRcv = new DatagramPacket(rcvBuf, rcvBuf.length);
    DatagramPacket packet = new DatagramPacket(buf, buf.length, serverAddr, port);

    try {
        socket.setSoTimeout(7000);
        startTime = System.currentTimeMillis();
        Logger.d("Sending packet, waiting for response ");
        for (i = 0; i < num; i++) {
            socket.send(packet);
        }
        for (i = 0; i < num; i++) {
            socket.receive(packetRcv);
            if (i == 0) {

                endTime = System.currentTimeMillis();
            }
        }
    } catch (SocketTimeoutException e) {
        Logger.d("Timed out");
        numLost += (num - i);
        socket.close();
    }
    Logger.d("Sending complete: " + endTime);

    retval[0] = endTime - startTime;
    retval[1] = numLost;

    return retval;
}

From source file:cai.flow.collector.Collector.java

/**
 *
 * @throws Throwable/*from  w  w w .  ja  va  2s  .com*/
 */
public void reader_loop() throws Throwable {
    DatagramSocket socket;

    try {
        try {
            socket = new DatagramSocket(localPort, localHost);
            socket.setReceiveBufferSize(receiveBufferSize);
        } catch (IOException exc) {
            logger.fatal("Reader - socket create error: " + localHost + ":" + localPort);
            logger.debug(exc);
            throw exc;
        }

        while (true) {
            byte[] buf = new byte[2048];// 
            DatagramPacket p = null;
            if (p == null) {
                p = new DatagramPacket(buf, buf.length);

                try {
                    socket.receive(p);
                } catch (IOException exc) {
                    logger.error("Reader - socket read error: " + exc.getMessage());
                    logger.debug(exc);
                    put_to_queue(null);// notifyAll
                    break;
                }
            }

            if (this.sampler.shouldDue()) {
                put_to_queue(p);
            }
            p = null;
        }
    } catch (Throwable e) {
        logger.error("Exception trying to abort collector");
        put_to_queue(null);
        throw e;
    }
}

From source file:com.mobiperf.measurements.RRCTask.java

/**
 * Sends a bunch of UDP packets of the size indicated and wait for the response.
 * /*from w  w  w.ja  v  a  2  s  . co m*/
 * Counts how long it takes for all the packets to return. PAckets are currently not labelled: the
 * total time is the time for the first packet to leave until the last packet arrives. AFter 7000
 * ms it is assumed packets are lost and the socket times out. In that case, the number of packets
 * lost is recorded.
 * 
 * @param serverAddr server to which to send the packets
 * @param size size of the packets
 * @param num number of packets to send
 * @param packetSize size of the packets sent
 * @param port port to send the packets to
 * @return first value: the amount of time to send all packets and get a response. second value:
 *         number of packets lost, on a timeout.
 * @throws IOException
 */
public static long[] sendMultiPackets(InetAddress serverAddr, int size, int num, int packetSize, int port)
        throws IOException {

    long startTime = 0;
    long endTime = 0;
    byte[] buf = new byte[size];
    byte[] rcvBuf = new byte[packetSize];
    long[] retval = { -1, -1 };
    long numLost = 0;
    int i = 0;
    long dataConsumedThisTask = 0;

    DatagramSocket socket = new DatagramSocket();
    DatagramPacket packetRcv = new DatagramPacket(rcvBuf, rcvBuf.length);
    DatagramPacket packet = new DatagramPacket(buf, buf.length, serverAddr, port);

    // number * (packet sent + packet received)
    dataConsumedThisTask += num * (size + packetSize);

    try {
        socket.setSoTimeout(7000);
        startTime = System.currentTimeMillis();
        Logger.d("Sending packet, waiting for response ");
        for (i = 0; i < num; i++) {
            socket.send(packet);
        }
        for (i = 0; i < num; i++) {
            socket.receive(packetRcv);
            if (i == 0) {

                endTime = System.currentTimeMillis();
            }
        }
    } catch (SocketTimeoutException e) {
        Logger.d("Timed out");
        numLost += (num - i);
        socket.close();
    }
    Logger.d("Sending complete: " + endTime);

    retval[0] = endTime - startTime;
    retval[1] = numLost;

    incrementData(dataConsumedThisTask);
    return retval;
}

From source file:org.rifidi.emulator.io.comm.ip.udp.UDPCommunicationTest.java

/**
 * Tests turning on the UDPCommunication while it is off.
 * //w  w  w .j a v a2s  .  c o  m
 *  
 */
public void testTurnOnWhenOff() {

    /* Data to send */
    byte[] dataToSend = message.getBytes();

    /* Error code -- gets modified if exceptions occur. */
    boolean error = false;

    /* Attempt to connect to the specified IP/Port using UDP */
    this.udpComm.turnOn();

    /* Allow server socket to fully start */
    synchronized (this) {
        try {
            this.wait(1000);
        } catch (InterruptedException e2) {
            /* Do nothing */
        }
        this.notifyAll();
    }

    /* Make a client */
    DatagramSocket clientSocket = null;
    try {
        clientSocket = new DatagramSocket(this.udpComm.getRemotePort());
    } catch (SocketException e) {
        logger.debug(this.getName() + ": " + e.getMessage());
        error = true;
    }

    /* Send out a packet of data */
    try {
        this.udpComm.getSendBuffer().addToBuffer(dataToSend);
    } catch (DataBufferInterruptedException dbie) {
        logger.debug(this.getName() + ": " + dbie.getMessage());
        error = true;
    }

    /* Receive the packet of data */
    if (clientSocket != null) {
        /* Set a timeout for receiving data */
        try {
            clientSocket.setSoTimeout(1000);
        } catch (SocketException e) {
            logger.debug(this.getName() + ": " + e.getMessage());
            error = true;
        }

        /* Make a new packet to hold the received data */
        DatagramPacket dataPacket = new DatagramPacket(new byte[1024], 1024);

        /* Attempt to receive the data */
        try {
            clientSocket.receive(dataPacket);
        } catch (IOException e) {
            logger.debug(this.getName() + ": " + e.getMessage());
            error = true;
        }

        /* Check that the data was received succesfully */
        if (!error) {
            logger.debug("Client received: " + new String(dataPacket.getData()));
        } else {
            logger.debug(this.getName() + ": client did not receive message.");
            error = true;
        }

        clientSocket.disconnect();

        clientSocket.close();
        clientSocket = null;

    }

    /* Check to see if any errors happened. */
    assertFalse(error);

}

From source file:com.t_oster.visicut.misc.Helper.java

public static List<String> findVisiCamInstances() {
    List<String> result = new LinkedList<String>();
    // Find the server using UDP broadcast
    try {//from  w w  w. ja v  a  2  s . c o m
        //Open a random port to send the package
        DatagramSocket c = new DatagramSocket();
        c.setBroadcast(true);

        byte[] sendData = "VisiCamDiscover".getBytes();

        //Try the 255.255.255.255 first
        try {
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
                    InetAddress.getByName("255.255.255.255"), 8888);
            c.send(sendPacket);
        } catch (Exception e) {
        }

        // Broadcast the message over all the network interfaces
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface networkInterface = interfaces.nextElement();
            if (networkInterface.isLoopback() || !networkInterface.isUp()) {
                continue; // Don't want to broadcast to the loopback interface
            }
            for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
                InetAddress broadcast = interfaceAddress.getBroadcast();
                if (broadcast == null) {
                    continue;
                }
                // Send the broadcast package!
                try {
                    DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, broadcast, 8888);
                    c.send(sendPacket);
                } catch (Exception e) {
                }
            }
        }
        //Wait for a response
        byte[] recvBuf = new byte[15000];
        c.setSoTimeout(3000);
        while (true) {
            DatagramPacket receivePacket = new DatagramPacket(recvBuf, recvBuf.length);
            try {
                c.receive(receivePacket);
                //Check if the message is correct
                String message = new String(receivePacket.getData()).trim();
                //Close the port!
                c.close();
                if (message.startsWith("http")) {
                    result.add(message);
                }
            } catch (SocketTimeoutException e) {
                break;
            }
        }
    } catch (IOException ex) {
    }
    return result;
}

From source file:org.cc86.MMC.client.Main.java

public static String serverDiscovery() {
    String res = "0.0.0.0";
    DatagramSocket c;
    // Find the server using UDP broadcast
    try {//from ww w  .j a va  2s .c  om
        //Open a random port to send the package
        c = new DatagramSocket();
        c.setBroadcast(true);

        byte[] sendData = "DISCOVER_MMC_REQUEST".getBytes();

        //Try the 255.255.255.255 first
        try {
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
                    InetAddress.getByName("255.255.255.255"), 0xCC86);
            c.send(sendPacket);
            l.info("Request packet sent to: 255.255.255.255 (DEFAULT)");
        } catch (Exception e) {
        }

        // Broadcast the message over all the network interfaces
        Enumeration interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface networkInterface = (NetworkInterface) interfaces.nextElement();

            if (networkInterface.isLoopback() || !networkInterface.isUp()) {
                continue; // Don't want to broadcast to the loopback interface
            }

            for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
                InetAddress broadcast = interfaceAddress.getBroadcast();
                if (broadcast == null) {
                    continue;
                }

                // Send the broadcast package!
                try {
                    DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, broadcast, 8888);
                    c.send(sendPacket);
                } catch (Exception e) {
                }

                l.info("Request packet sent to: " + broadcast.getHostAddress() + "; Interface: "
                        + networkInterface.getDisplayName());
            }
        }

        l.info("Done looping over all network interfaces. Now waiting for a reply!");

        //Wait for a response
        byte[] recvBuf = new byte[15000];
        DatagramPacket receivePacket = new DatagramPacket(recvBuf, recvBuf.length);
        c.receive(receivePacket);

        //We have a response
        l.info("Broadcast response from server: " + receivePacket.getAddress().getHostAddress());

        //Check if the message is correct
        String message = new String(receivePacket.getData()).trim();
        if (message.equals("DISCOVER_MMC_RESPONSE")) {
            //DO SOMETHING WITH THE SERVER'S IP (for example, store it in your controller)
            res = (receivePacket.getAddress() + "").substring(1);
        }

        //Close the port!
        c.close();
    } catch (IOException ex) {

    }
    return res;
}

From source file:snapshotTools.java

private String callOvnmanager(String node, String action) {
    String result = "";
    DatagramSocket socket = null;
    int serverPort = 9999;
    DatagramPacket packet2Send;/*from www  .  j  a  v  a2 s .c  om*/
    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:com.clustercontrol.agent.Agent.java

/**
 * ??awakeAgent?//from   w w  w .  j a  va 2  s .  c  o m
 * Agent.properties???UDP?24005??????????(releaseLatch)
 * ????ReceiveTopic????Topic????
 */
public void waitAwakeAgent() {
    final int BUFSIZE = 1;

    byte[] buf = new byte[BUFSIZE];
    InetAddress cAddr; // ??IP
    int cPort; // ???
    DatagramSocket sock = null;
    boolean flag = true;
    int port = 24005;

    int awakeDelay = 1000;

    try {
        String awakeDelayStr = AgentProperties.getProperty("awake.delay", Integer.toString(1000));
        awakeDelay = Integer.parseInt(awakeDelayStr);
        m_log.info("awake.delay = " + awakeDelay + " msec");
    } catch (NumberFormatException e) {
        m_log.error("awake.delay", e);
    }

    while (true) {
        /*
         * UDP???flag?true??
         * ?????flag?false?????getTopic(releaseLatch)?
         * 
         * UDP???????getTopic????????
         * ??????
         */
        try {
            if (sock != null && port != awakePort) {
                sock.close();
                sock = null;
            }
            if (sock == null || !sock.isBound()) {
                port = awakePort;
                sock = new DatagramSocket(port);
                sock.setSoTimeout(awakeDelay);
            }
            DatagramPacket recvPacket = new DatagramPacket(buf, BUFSIZE);
            sock.receive(recvPacket);
            cAddr = recvPacket.getAddress();
            cPort = recvPacket.getPort();
            flag = true;
            m_log.info("waitAwakeAgent (" + cAddr.getHostAddress() + " onPort=" + cPort + ") buf.length="
                    + buf.length);
        } catch (SocketTimeoutException e) {
            if (flag) {
                m_log.info("waitAwakeAgent packet end");
                m_receiveTopic.releaseLatch();
                flag = false;
            }
        } catch (Exception e) {
            String msg = "waitAwakeAgent port=" + awakePort + ", " + e.getClass().getSimpleName() + ", "
                    + e.getMessage();
            if (e instanceof BindException) {
                m_log.warn(msg);
            } else {
                m_log.warn(msg, e);
            }
            try {
                Thread.sleep(60 * 1000);
            } catch (InterruptedException e1) {
                m_log.warn(e1, e1);
            }
        }
    }
}

From source file:vitro.vgw.wsiadapter.WSIAdapterCoap.java

/**
 * WSIAdapter interface//w  w  w . j  av  a 2  s .  com
 */

public List<Node> getAvailableNodeList() throws WSIAdapterException {

    logger.info("Getting available nodes...");

    nodesList = new ArrayList<Node>();

    List<String> wsnProxyList = new LinkedList<String>();
    wsnProxyList.add(Network.WLAB_OFFICE_PROXY_ADDRESS);
    wsnProxyList.add(Network.WLAB_LAB_PROXY_ADDRESS);

    DatagramSocket serverSocket = null;
    DatagramSocket clientSocket = null;
    String cmdString = "route";

    for (int i = 0; i < wsnProxyList.size(); i++) {
        try {
            serverSocket = new DatagramSocket(Constants.UDPSHELL_VGW_PORT);

            String hostProxyString = wsnProxyList.get(i);
            InetAddress hostProxy = InetAddress.getByName(hostProxyString);

            clientSocket = new DatagramSocket();
            byte[] bufCmd = new byte[10];
            bufCmd = cmdString.getBytes();
            DatagramPacket outcomingPacket = new DatagramPacket(bufCmd, bufCmd.length, hostProxy,
                    Constants.PROXY_UDPFORWARDER_PORT);
            clientSocket.send(outcomingPacket);

            boolean otherPackets = false;

            serverSocket.setSoTimeout(Constants.PROXY_RESPONSE_TIMEOUT);
            logger.info("Quering " + hostProxyString);
            try {
                byte[] bufAck = new byte[10];
                DatagramPacket ackPacket = new DatagramPacket(bufAck, bufAck.length);
                serverSocket.receive(ackPacket);
                String ackString = new String(ackPacket.getData()).trim();
                if (ackString.equals("ack")) {
                    otherPackets = true;
                }
            } catch (SocketTimeoutException e) {
                logger.warn(e.getMessage());
            }

            serverSocket.setSoTimeout(0);

            while (otherPackets) {
                try {
                    byte[] bufIncoming = new byte[1000];
                    DatagramPacket incomingPacket = new DatagramPacket(bufIncoming, bufIncoming.length);
                    serverSocket.receive(incomingPacket);
                    String currentNodeIP = new String(incomingPacket.getData()).trim();
                    if (!currentNodeIP.equals("end")) {
                        logger.info("Node: " + currentNodeIP);
                        nodesList.add(new Node(currentNodeIP));
                    } else {
                        otherPackets = false;
                        logger.info("No other nodes from " + hostProxyString);
                    }
                } catch (IOException e) {
                    logger.error(e.getMessage());
                }
            }

        } catch (UnknownHostException e) {
            logger.warn(e.getMessage() + " is not reachable.");
        } catch (SocketException e) {
            logger.error(e.getMessage());
        } catch (IOException e) {
            logger.error(e.getMessage());
        } finally {
            if (serverSocket != null) {
                serverSocket.close();
            }
            if (clientSocket != null) {
                clientSocket.close();
            }
        }
    }

    return nodesList;
}

From source file:org.opendaylight.lispflowmapping.integrationtest.MappingServiceIntegrationTest.java

License:asdf

private DatagramPacket receivePacket(DatagramSocket receivedSocket, int timeout) throws SocketTimeoutException {
    try {/*from w  ww .ja  va  2s. c o m*/
        byte[] buffer = new byte[4096];
        DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length);
        LOG.trace("Waiting for packet from socket...");
        receivedSocket.setSoTimeout(timeout);
        receivedSocket.receive(receivePacket);
        LOG.trace("Recieved packet from socket!");
        return receivePacket;
    } catch (SocketTimeoutException ste) {
        throw ste;
    } catch (Throwable t) {
        fail();
        return null;
    }
}