Java Code Examples for java.net.MulticastSocket#receive()

The following examples show how to use java.net.MulticastSocket#receive() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SsdpDiscovery.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
static Map<String, Map<String, String>> retrieveResponse() throws Exception {
    String response = null;
    Map<String, Map<String, String>> result = new HashMap<String, Map<String, String>>();
    MulticastSocket recSocket = setUpSocket();

    int i = 0;
    logger.debug("Retrieving response");
    while (i < 10) {
        byte[] buf = new byte[2048];
        DatagramPacket input = new DatagramPacket(buf, buf.length);
        try {
            recSocket.receive(input);
            response = new String(input.getData());
            Map<String, String> parsedResponse = parseResponse(response);
            result.put(parsedResponse.get("IP"), parsedResponse);
        } catch (SocketTimeoutException e) {
            if (i >= 10) {
                break;
            }
            i++;
        }
    }
    logger.debug("Response retrieved: {}", result);
    return result;
}
 
Example 2
Source File: Two.java    From JavaBase with MIT License 6 votes vote down vote up
public static void main(String[] args) {
  try {
    InetAddress group = InetAddress.getByName(address);
    MulticastSocket multicastSocket = new MulticastSocket(port);
    multicastSocket.joinGroup(group);
    byte[] buffer = new byte[1024];

    while (true) {
      DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
      multicastSocket.receive(packet);

      String str = new String(packet.getData(), 0, packet.getLength());
      log.info("str={}", str);
    }
  } catch (Exception e) {
    log.error("", e);
  }
}
 
Example 3
Source File: JdpTestCase.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public void run() throws Exception {
    log.fine("Test started.");
    log.fine("Listening for multicast packets at " + connection.address.getHostAddress()
            + ":" + String.valueOf(connection.port));
    log.fine(initialLogMessage());
    log.fine("Pause in between packets is: " + connection.pauseInSeconds + " seconds.");

    startTime = System.currentTimeMillis();
    timeOut = connection.pauseInSeconds * TIME_OUT_FACTOR;
    log.fine("Timeout set to " + String.valueOf(timeOut) + " seconds.");

    MulticastSocket socket = connection.connectWithTimeout(timeOut * 1000);

    byte[] buffer = new byte[BUFFER_LENGTH];
    DatagramPacket datagram = new DatagramPacket(buffer, buffer.length);

    do {
        try {
            socket.receive(datagram);
            onReceived(extractUDPpayload(datagram));
        } catch (SocketTimeoutException e) {
            onSocketTimeOut(e);
        }

        if (hasTestLivedLongEnough()) {
            shutdown();
        }

    } while (shouldContinue());
    log.fine("Test ended successfully.");
}
 
Example 4
Source File: SsdpDiscovery.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Scans all messages that arrive on the socket and scans them for the
 * search keywords. The search is not case sensitive.
 * 
 * @param socket
 *            The socket where the answers arrive.
 * @param keywords
 *            The keywords to be searched for.
 * @return
 * @throws IOException
 */
private String scanResposesForKeywords(MulticastSocket socket, String... keywords) throws IOException {
    // In the worst case a SocketTimeoutException raises
    socket.setSoTimeout(2000);
    do {
        logger.debug("Got an answer message.");
        byte[] rxbuf = new byte[8192];
        DatagramPacket packet = new DatagramPacket(rxbuf, rxbuf.length);
        socket.receive(packet);
        String foundIp = analyzePacket(packet, keywords);
        if (foundIp != null) {
            return foundIp;
        }
    } while (true);
}
 
Example 5
Source File: JdpTestCase.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
public void run() throws Exception {
    log.fine("Test started.");
    log.fine("Listening for multicast packets at " + connection.address.getHostAddress()
            + ":" + String.valueOf(connection.port));
    log.fine(initialLogMessage());
    log.fine("Pause in between packets is: " + connection.pauseInSeconds + " seconds.");

    startTime = System.currentTimeMillis();
    timeOut = connection.pauseInSeconds * TIME_OUT_FACTOR;
    log.fine("Timeout set to " + String.valueOf(timeOut) + " seconds.");

    MulticastSocket socket = connection.connectWithTimeout(timeOut * 1000);

    byte[] buffer = new byte[BUFFER_LENGTH];
    DatagramPacket datagram = new DatagramPacket(buffer, buffer.length);

    do {
        try {
            socket.receive(datagram);
            onReceived(extractUDPpayload(datagram));
        } catch (SocketTimeoutException e) {
            onSocketTimeOut(e);
        }

        if (hasTestLivedLongEnough()) {
            shutdown();
        }

    } while (shouldContinue());
    log.fine("Test ended successfully.");
}
 
Example 6
Source File: JdpTestCase.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public void run() throws Exception {
    log.fine("Test started.");
    log.fine("Listening for multicast packets at " + connection.address.getHostAddress()
            + ":" + String.valueOf(connection.port));
    log.fine(initialLogMessage());
    log.fine("Pause in between packets is: " + connection.pauseInSeconds + " seconds.");

    startTime = System.currentTimeMillis();
    timeOut = connection.pauseInSeconds * TIME_OUT_FACTOR;
    log.fine("Timeout set to " + String.valueOf(timeOut) + " seconds.");

    MulticastSocket socket = connection.connectWithTimeout(timeOut * 1000);

    byte[] buffer = new byte[BUFFER_LENGTH];
    DatagramPacket datagram = new DatagramPacket(buffer, buffer.length);

    do {
        try {
            socket.receive(datagram);
            onReceived(extractUDPpayload(datagram));
        } catch (SocketTimeoutException e) {
            onSocketTimeOut(e);
        }

        if (hasTestLivedLongEnough()) {
            shutdown();
        }

    } while (shouldContinue());
    log.fine("Test ended successfully.");
}
 
Example 7
Source File: Multicast.java    From Bitcoin with Apache License 2.0 5 votes vote down vote up
/**
 * Blocking call
 */
public static boolean recvData(MulticastSocket s, byte[] buffer) throws IOException {
    s.setSoTimeout(100);
    // Create a DatagramPacket and do a receive
    final DatagramPacket pack = new DatagramPacket(buffer, buffer.length);
    try {
        s.receive(pack);
    } catch (SocketTimeoutException e) {
        return false;
    }
    // We have finished receiving data
    return true;
}
 
Example 8
Source File: JdpTestCase.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public void run() throws Exception {
    log.fine("Test started.");
    log.fine("Listening for multicast packets at " + connection.address.getHostAddress()
            + ":" + String.valueOf(connection.port));
    log.fine(initialLogMessage());
    log.fine("Pause in between packets is: " + connection.pauseInSeconds + " seconds.");

    startTime = System.currentTimeMillis();
    timeOut = connection.pauseInSeconds * TIME_OUT_FACTOR;
    log.fine("Timeout set to " + String.valueOf(timeOut) + " seconds.");

    MulticastSocket socket = connection.connectWithTimeout(timeOut * 1000);

    byte[] buffer = new byte[BUFFER_LENGTH];
    DatagramPacket datagram = new DatagramPacket(buffer, buffer.length);

    do {
        try {
            socket.receive(datagram);
            onReceived(extractUDPpayload(datagram));
        } catch (SocketTimeoutException e) {
            onSocketTimeOut(e);
        }

        if (hasTestLivedLongEnough()) {
            shutdown();
        }

    } while (shouldContinue());
    log.fine("Test ended successfully.");
}
 
Example 9
Source File: JdpTestCase.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public void run() throws Exception {
    log.fine("Test started.");
    log.fine("Listening for multicast packets at " + connection.address.getHostAddress()
            + ":" + String.valueOf(connection.port));
    log.fine(initialLogMessage());
    log.fine("Pause in between packets is: " + connection.pauseInSeconds + " seconds.");

    startTime = System.currentTimeMillis();
    timeOut = connection.pauseInSeconds * TIME_OUT_FACTOR;
    log.fine("Timeout set to " + String.valueOf(timeOut) + " seconds.");

    MulticastSocket socket = connection.connectWithTimeout(timeOut * 1000);

    byte[] buffer = new byte[BUFFER_LENGTH];
    DatagramPacket datagram = new DatagramPacket(buffer, buffer.length);

    do {
        try {
            socket.receive(datagram);
            onReceived(extractUDPpayload(datagram));
        } catch (SocketTimeoutException e) {
            onSocketTimeOut(e);
        }

        if (hasTestLivedLongEnough()) {
            shutdown();
        }

    } while (shouldContinue());
    log.fine("Test ended successfully.");
}
 
Example 10
Source File: JdpTestCase.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public void run() throws Exception {
    log.fine("Test started.");
    log.fine("Listening for multicast packets at " + connection.address.getHostAddress()
            + ":" + String.valueOf(connection.port));
    log.fine(initialLogMessage());
    log.fine("Pause in between packets is: " + connection.pauseInSeconds + " seconds.");

    startTime = System.currentTimeMillis();
    timeOut = connection.pauseInSeconds * TIME_OUT_FACTOR;
    log.fine("Timeout set to " + String.valueOf(timeOut) + " seconds.");

    MulticastSocket socket = connection.connectWithTimeout(timeOut * 1000);

    byte[] buffer = new byte[BUFFER_LENGTH];
    DatagramPacket datagram = new DatagramPacket(buffer, buffer.length);

    do {
        try {
            socket.receive(datagram);
            onReceived(extractUDPpayload(datagram));
        } catch (SocketTimeoutException e) {
            onSocketTimeOut(e);
        }

        if (hasTestLivedLongEnough()) {
            shutdown();
        }

    } while (shouldContinue());
    log.fine("Test ended successfully.");
}
 
Example 11
Source File: JdpTestCase.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public void run() throws Exception {
    log.fine("Test started.");
    log.fine("Listening for multicast packets at " + connection.address.getHostAddress()
            + ":" + String.valueOf(connection.port));
    log.fine(initialLogMessage());
    log.fine("Pause in between packets is: " + connection.pauseInSeconds + " seconds.");

    startTime = System.currentTimeMillis();
    timeOut = connection.pauseInSeconds * TIME_OUT_FACTOR;
    log.fine("Timeout set to " + String.valueOf(timeOut) + " seconds.");

    MulticastSocket socket = connection.connectWithTimeout(timeOut * 1000);

    byte[] buffer = new byte[BUFFER_LENGTH];
    DatagramPacket datagram = new DatagramPacket(buffer, buffer.length);

    do {
        try {
            socket.receive(datagram);
            onReceived(extractUDPpayload(datagram));
        } catch (SocketTimeoutException e) {
            onSocketTimeOut(e);
        }

        if (hasTestLivedLongEnough()) {
            shutdown();
        }

    } while (shouldContinue());
    log.fine("Test ended successfully.");
}
 
Example 12
Source File: UDP.java    From openvisualtraceroute with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static void test() throws Exception {
	final String hostname = "google.com";
	final String localhost = "localhost";
	final MulticastSocket datagramSocket = new MulticastSocket();
	datagramSocket.setSoTimeout(10000);
	short ttl = 1;
	final InetAddress receiverAddress = InetAddress.getByName(hostname);
	while (ttl < 100) {
		try {
			byte[] buffer = "0123456789".getBytes();
			datagramSocket.setTimeToLive(ttl++);
			final DatagramPacket sendPacket = new DatagramPacket(buffer, buffer.length, receiverAddress, 80);

			datagramSocket.send(sendPacket);

			buffer = new byte[10];
			final DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length);

			datagramSocket.receive(receivePacket);
			System.out.println("ttl=" + ttl + " address=" + receivePacket.getAddress().getHostAddress() + " data="
					+ new String(receivePacket.getData()));
			Thread.sleep(1000);
		} catch (final SocketTimeoutException e) {
			System.out.println("timeout ttl=" + ttl);
		}
	}
}
 
Example 13
Source File: JdpTestCase.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public void run() throws Exception {
    log.fine("Test started.");
    log.fine("Listening for multicast packets at " + connection.address.getHostAddress()
            + ":" + String.valueOf(connection.port));
    log.fine(initialLogMessage());
    log.fine("Pause in between packets is: " + connection.pauseInSeconds + " seconds.");

    startTime = System.currentTimeMillis();
    timeOut = connection.pauseInSeconds * TIME_OUT_FACTOR;
    log.fine("Timeout set to " + String.valueOf(timeOut) + " seconds.");

    MulticastSocket socket = connection.connectWithTimeout(timeOut * 1000);

    byte[] buffer = new byte[BUFFER_LENGTH];
    DatagramPacket datagram = new DatagramPacket(buffer, buffer.length);

    do {
        try {
            socket.receive(datagram);
            onReceived(extractUDPpayload(datagram));
        } catch (SocketTimeoutException e) {
            onSocketTimeOut(e);
        }

        if (hasTestLivedLongEnough()) {
            shutdown();
        }

    } while (shouldContinue());
    log.fine("Test ended successfully.");
}
 
Example 14
Source File: JdpTestCase.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public void run() throws Exception {
    log.fine("Test started.");
    log.fine("Listening for multicast packets at " + connection.address.getHostAddress()
            + ":" + String.valueOf(connection.port));
    log.fine(initialLogMessage());
    log.fine("Pause in between packets is: " + connection.pauseInSeconds + " seconds.");

    startTime = System.currentTimeMillis();
    timeOut = connection.pauseInSeconds * TIME_OUT_FACTOR;
    log.fine("Timeout set to " + String.valueOf(timeOut) + " seconds.");

    MulticastSocket socket = connection.connectWithTimeout(timeOut * 1000);

    byte[] buffer = new byte[BUFFER_LENGTH];
    DatagramPacket datagram = new DatagramPacket(buffer, buffer.length);

    do {
        try {
            socket.receive(datagram);
            onReceived(extractUDPpayload(datagram));
        } catch (SocketTimeoutException e) {
            onSocketTimeOut(e);
        }

        if (hasTestLivedLongEnough()) {
            shutdown();
        }

    } while (shouldContinue());
    log.fine("Test ended successfully.");
}
 
Example 15
Source File: JdpTestCase.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public void run() throws Exception {
    log.fine("Test started.");
    log.fine("Listening for multicast packets at " + connection.address.getHostAddress()
            + ":" + String.valueOf(connection.port));
    log.fine(initialLogMessage());
    log.fine("Pause in between packets is: " + connection.pauseInSeconds + " seconds.");

    startTime = System.currentTimeMillis();
    timeOut = connection.pauseInSeconds * TIME_OUT_FACTOR;
    log.fine("Timeout set to " + String.valueOf(timeOut) + " seconds.");

    MulticastSocket socket = connection.connectWithTimeout(timeOut * 1000);

    byte[] buffer = new byte[BUFFER_LENGTH];
    DatagramPacket datagram = new DatagramPacket(buffer, buffer.length);

    do {
        try {
            socket.receive(datagram);
            onReceived(extractUDPpayload(datagram));
        } catch (SocketTimeoutException e) {
            onSocketTimeOut(e);
        }

        if (hasTestLivedLongEnough()) {
            shutdown();
        }

    } while (shouldContinue());
    log.fine("Test ended successfully.");
}
 
Example 16
Source File: JdpTestCase.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public void run() throws Exception {
    log.fine("Test started.");
    log.fine("Listening for multicast packets at " + connection.address.getHostAddress()
            + ":" + String.valueOf(connection.port));
    log.fine(initialLogMessage());
    log.fine("Pause in between packets is: " + connection.pauseInSeconds + " seconds.");

    startTime = System.currentTimeMillis();
    timeOut = connection.pauseInSeconds * TIME_OUT_FACTOR;
    log.fine("Timeout set to " + String.valueOf(timeOut) + " seconds.");

    MulticastSocket socket = connection.connectWithTimeout(timeOut * 1000);

    byte[] buffer = new byte[BUFFER_LENGTH];
    DatagramPacket datagram = new DatagramPacket(buffer, buffer.length);

    do {
        try {
            socket.receive(datagram);
            onReceived(extractUDPpayload(datagram));
        } catch (SocketTimeoutException e) {
            onSocketTimeOut(e);
        }

        if (hasTestLivedLongEnough()) {
            shutdown();
        }

    } while (shouldContinue());
    log.fine("Test ended successfully.");
}
 
Example 17
Source File: JdpTestCase.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public void run() throws Exception {
    log.fine("Test started.");
    log.fine("Listening for multicast packets at " + connection.address.getHostAddress()
            + ":" + String.valueOf(connection.port));
    log.fine(initialLogMessage());
    log.fine("Pause in between packets is: " + connection.pauseInSeconds + " seconds.");

    startTime = System.currentTimeMillis();
    timeOut = connection.pauseInSeconds * TIME_OUT_FACTOR;
    log.fine("Timeout set to " + String.valueOf(timeOut) + " seconds.");

    MulticastSocket socket = connection.connectWithTimeout(timeOut * 1000);

    byte[] buffer = new byte[BUFFER_LENGTH];
    DatagramPacket datagram = new DatagramPacket(buffer, buffer.length);

    do {
        try {
            socket.receive(datagram);
            onReceived(extractUDPpayload(datagram));
        } catch (SocketTimeoutException e) {
            onSocketTimeOut(e);
        }

        if (hasTestLivedLongEnough()) {
            shutdown();
        }

    } while (shouldContinue());
    log.fine("Test ended successfully.");
}
 
Example 18
Source File: JdpTestCase.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public void run() throws Exception {
    log.fine("Test started.");
    log.fine("Listening for multicast packets at " + connection.address.getHostAddress()
            + ":" + String.valueOf(connection.port));
    log.fine(initialLogMessage());
    log.fine("Pause in between packets is: " + connection.pauseInSeconds + " seconds.");

    startTime = System.currentTimeMillis();
    timeOut = connection.pauseInSeconds * TIME_OUT_FACTOR;
    log.fine("Timeout set to " + String.valueOf(timeOut) + " seconds.");

    MulticastSocket socket = connection.connectWithTimeout(timeOut * 1000);

    byte[] buffer = new byte[BUFFER_LENGTH];
    DatagramPacket datagram = new DatagramPacket(buffer, buffer.length);

    do {
        try {
            socket.receive(datagram);
            onReceived(extractUDPpayload(datagram));
        } catch (SocketTimeoutException e) {
            onSocketTimeOut(e);
        }

        if (hasTestLivedLongEnough()) {
            shutdown();
        }

    } while (shouldContinue());
    log.fine("Test ended successfully.");
}
 
Example 19
Source File: WirelessHidService.java    From WirelessHid with Apache License 2.0 4 votes vote down vote up
public void startDiscover() {

            try {
                mMulticastSocket = new MulticastSocket(Constant.HID_MULTICAST_PORT);
                group = InetAddress.getByName(Constant.HID_MULTICAST_ADDRESS);
                mMulticastSocket.joinGroup(group);
            } catch (IOException e) {
                e.printStackTrace();
                return;
            }

            listenerThread = new Thread(new Runnable() {
                // listen response from pc.
                @Override
                public void run() {
                    try {
                        DatagramPacket packet;
                        packet = new DatagramPacket(new byte[256], 256);

                        while (true) {
                            mMulticastSocket.receive(packet);

                            String rsp = new String(packet.getData()).trim();
                            Log.d(TAG, "rsp: " + rsp);
                            if (Constant.HID_SERVICE_DISCOVERY_RSP.equals(rsp)) {
                                Log.d(TAG, "get response from pc.");
                                break;
                            } else {
                                Log.d(TAG, "It is not a valid response, just ignore it.");
                                packet.setData(new byte[256]);
                            }
                        }

                        // send message to activity to stop progress dialog.
                        if (mUIHandler != null) {
                            mUIHandler.obtainMessage(MainActivity.MSG_FOUND_SERVICE).sendToTarget();
                        }

                        mPCIPAddress = packet.getAddress();
                        Log.d(TAG, "pc ip address: " + packet.getSocketAddress().toString());

                        // interrupt scanner thread to stop scan cause we have found pc.
                        scannerThread.interrupt();

                        // start data send thread.
                        new DataSendThread().start();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
            scannerThread = new Thread(new Runnable() {
                // pc finder thread.
                @Override
                public void run() {
                    try {
                        DatagramPacket packet = new DatagramPacket(Constant.HID_SERVICE_DISCOVERY_REQ.getBytes(),
                                Constant.HID_SERVICE_DISCOVERY_REQ.length(),
                                group, Constant.HID_MULTICAST_PORT);
                        while (true) {
                            if (scannerThread.isInterrupted()) {
                                break;
                            }

                            Log.d(TAG, "discovery pc......");
                            mMulticastSocket.send(packet);

                            // try again after 2s.
                            try {
                                Thread.sleep(2000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                                break;
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });

            // start discover thread.
            scannerThread.start();
            listenerThread.start();
        }