List of usage examples for java.net MulticastSocket setSoTimeout
public synchronized void setSoTimeout(int timeout) throws SocketException
From source file:de.jaetzold.networking.SimpleServiceDiscovery.java
/** * Send a SSDP search message with the given search target (ST) and return a list of received responses. *///w ww .ja v a2 s . com public Map<String, URL> discover(String searchTarget) { Log.d("HUE", "ServiceDiscovery.discover"); final InetSocketAddress address; // standard multicast port for SSDP try { // multicast address with administrative scope address = new InetSocketAddress(InetAddress.getByName(MULTICAST_ADDRESS), MULTICAST_PORT); //address = InetAddress.getByName(MULTICAST_ADDRESS); } catch (UnknownHostException e) { e.printStackTrace(); throw new IllegalStateException("Can not get multicast address", e); } final MulticastSocket socket; try { socket = new MulticastSocket(null); InetAddress localhost = getAndroidLocalIP(); InetSocketAddress srcAddress = new InetSocketAddress(localhost, MULTICAST_PORT); Log.d("HUE", "" + srcAddress.getAddress()); socket.bind(srcAddress); Log.d("HUE", "step 1"); } catch (IOException e) { e.printStackTrace(); throw new IllegalStateException("Can not create multicast socket"); } try { socket.setSoTimeout(socketTimeout); Log.d("HUE", "step 2"); } catch (SocketException e) { e.printStackTrace(); throw new IllegalStateException("Can not set socket timeout", e); } try { socket.joinGroup(InetAddress.getByName(MULTICAST_ADDRESS)); Log.d("HUE", "step 3"); } catch (IOException e) { e.printStackTrace(); throw new IllegalStateException("Can not make multicast socket joinGroup " + address, e); } try { socket.setTimeToLive(ttl); Log.d("HUE", "step 4"); } catch (IOException e) { e.printStackTrace(); throw new IllegalStateException("Can not set TTL " + ttl, e); } final byte[] transmitBuffer; try { transmitBuffer = constructSearchMessage(searchTarget).getBytes(CHARSET_NAME); Log.d("HUE", "step 5"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); throw new IllegalStateException("WTF? " + CHARSET_NAME + " is not supported?", e); } DatagramPacket packet = null; try { packet = new DatagramPacket(transmitBuffer, transmitBuffer.length, address); Log.d("HUE", "step 6"); } catch (SocketException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { socket.send(packet); Log.d("HUE", "step 7"); } catch (IOException e) { e.printStackTrace(); throw new IllegalStateException("Can not send search request", e); } Map<String, URL> result = new HashMap<String, URL>(); byte[] receiveBuffer = new byte[1536]; while (true) { try { Log.d("HUE", "sending packets"); final DatagramPacket receivePacket = new DatagramPacket(receiveBuffer, receiveBuffer.length, InetAddress.getByName(MULTICAST_ADDRESS), MULTICAST_PORT); socket.receive(receivePacket); //Log.d("HUE", new String(receivePacket.getData())); HueBridge response = parseResponsePacket(receivePacket); if (response != null) { Log.d("HUE", "resonse not null"); ////System.out.println("resonse not null"); result.put(response.getUDN(), response.getBaseUrl()); } else { Log.d("HUE", "no bridge"); } } catch (SocketTimeoutException e) { Log.e("HUE", "timeout exception"); break; } catch (IOException e) { throw new IllegalStateException("Problem receiving search responses", e); } } return result; }
From source file:org.nebulaframework.discovery.multicast.MulticastDiscovery.java
/** * Discovery Process to identify Clusters with in * network.//from w w w . j a v a 2 s.c o m * * @throws IOException if occurred during operation */ private void doDiscover() throws IOException { // Send Request byte[] greet = GREET_MSG.getBytes("UTF-8"); DatagramPacket request = new DatagramPacket(greet, greet.length, SERVICE_REQUEST_IP, SERVICE_PORT); MulticastSocket reqSock = new MulticastSocket(); reqSock.send(request); // Wait for Response MulticastSocket resSock = new MulticastSocket(SERVICE_PORT); resSock.joinGroup(SERVICE_RESPONSE_IP); // 9 = # of bytes for an IP Address + 5 byte port DatagramPacket response = new DatagramPacket(new byte[9], 9); // Receive resSock.setSoTimeout((int) TIMEOUT); try { resSock.receive(response); } catch (SocketTimeoutException e) { log.debug("[MulticastDiscovery] Receive Timeout"); return; } byte[] data = response.getData(); byte[] ipBytes = Arrays.copyOfRange(data, 0, 4); byte[] portBytes = Arrays.copyOfRange(data, 4, 9); InetAddress ip = InetAddress.getByAddress(ipBytes); StringBuilder sb = new StringBuilder(ip.getHostAddress()); sb.append(":"); for (byte b : portBytes) { sb.append(b); } this.cluster = sb.toString(); }
From source file:org.nebulaframework.discovery.multicast.MulticastDiscovery.java
/** * Attempts to discover peer clusters using Multicast * Discovery. Each discovered Cluster will be notified * to the {@code PeerClusterService} of the * ClusterManager./* ww w . j a v a2 s .co m*/ * * @throws IOException if occurred during process */ public static void discoverPeerClusters() throws IOException { // Only allowed for ClusterManagers if (!Grid.isClusterManager()) { throw new UnsupportedOperationException( "Multicast Discovery Service can be enabled only for ClusterManagers"); } log.info("[MulticastDiscovery] Discovering Peer Clusters..."); // Send Request byte[] greet = GREET_MSG.getBytes("UTF-8"); DatagramPacket request = new DatagramPacket(greet, greet.length, SERVICE_REQUEST_IP, SERVICE_PORT); MulticastSocket reqSock = new MulticastSocket(); reqSock.send(request); // Response Socket MulticastSocket resSock = new MulticastSocket(SERVICE_PORT); resSock.joinGroup(SERVICE_RESPONSE_IP); // 9 = # of bytes for an IP Address + 5 byte port DatagramPacket response = new DatagramPacket(new byte[9], 9); // Set Socket Timeout resSock.setSoTimeout((int) TIMEOUT); try { // Loop until Socket Timeout Occurs while (true) { // Receive resSock.receive(response); processPeerResponse(response.getData()); } } catch (SocketTimeoutException e) { log.debug("[MulticastDiscovery] Receive Timeout"); return; } finally { log.info("[MulticastDiscovery] Peer Cluster Discovery Complete"); } }
From source file:org.openhab.binding.hue.internal.tools.SsdpDiscovery.java
/** * Broadcasts a SSDP discovery message into the network to find provided * services.//w w w . j a v a 2s.c o m * * @return The Socket the answers will arrive at. * @throws UnknownHostException * @throws IOException * @throws SocketException * @throws UnsupportedEncodingException */ private MulticastSocket sendDiscoveryBroacast() throws UnknownHostException, IOException, SocketException, UnsupportedEncodingException { InetAddress multicastAddress = InetAddress.getByName("239.255.255.250"); final int port = 1900; MulticastSocket socket = new MulticastSocket(port); socket.setReuseAddress(true); socket.setSoTimeout(130000); socket.joinGroup(multicastAddress); byte[] requestMessage = DISCOVER_MESSAGE.getBytes("UTF-8"); DatagramPacket datagramPacket = new DatagramPacket(requestMessage, requestMessage.length, multicastAddress, port); socket.send(datagramPacket); return socket; }
From source file:org.openhab.binding.hue.internal.tools.SsdpDiscovery.java
/** * Scans all messages that arrive on the socket and scans them for the * search keywords. The search is not case sensitive. * //from ww w .j av a2s. com * @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); }
From source file:org.openhab.binding.wemo.internal.WemoBinding.java
public void wemoDiscovery() { logger.debug("wemoDiscovery() is called!"); try {//from www. jav a2 s . com final int SSDP_PORT = 1900; final int SSDP_SEARCH_PORT = 1901; // Broadcast address final String SSDP_IP = "239.255.255.250"; // Connection timeout int TIMEOUT = 1000; // Send from localhost:1901 InetAddress localhost = InetAddress.getLocalHost(); InetSocketAddress srcAddress = new InetSocketAddress(localhost, SSDP_SEARCH_PORT); // Send to 239.255.255.250:1900 InetSocketAddress dstAddress = new InetSocketAddress(InetAddress.getByName(SSDP_IP), SSDP_PORT); // Request-Packet-Constructor StringBuffer discoveryMessage = new StringBuffer(); discoveryMessage.append("M-SEARCH * HTTP/1.1\r\n"); discoveryMessage.append("HOST: " + SSDP_IP + ":" + SSDP_PORT + "\r\n"); discoveryMessage.append("MAN: \"ssdp:discover\"\r\n"); discoveryMessage.append("MX: 5\r\n"); discoveryMessage.append("ST: urn:Belkin:service:basicevent:1\r\n"); discoveryMessage.append("\r\n"); logger.trace("Request: {}", discoveryMessage.toString()); byte[] discoveryMessageBytes = discoveryMessage.toString().getBytes(); DatagramPacket discoveryPacket = new DatagramPacket(discoveryMessageBytes, discoveryMessageBytes.length, dstAddress); // Send multi-cast packet MulticastSocket multicast = null; try { multicast = new MulticastSocket(null); multicast.bind(srcAddress); logger.trace("Source-Address = '{}'", srcAddress); multicast.setTimeToLive(5); logger.trace("Send multicast request."); multicast.send(discoveryPacket); } finally { logger.trace("Multicast ends. Close connection."); multicast.disconnect(); multicast.close(); } // Response-Listener MulticastSocket wemoReceiveSocket = null; DatagramPacket receivePacket = null; try { wemoReceiveSocket = new MulticastSocket(SSDP_SEARCH_PORT); wemoReceiveSocket.setTimeToLive(10); wemoReceiveSocket.setSoTimeout(TIMEOUT); logger.debug("Send datagram packet."); wemoReceiveSocket.send(discoveryPacket); while (true) { try { logger.debug("Receive SSDP Message."); receivePacket = new DatagramPacket(new byte[2048], 2048); wemoReceiveSocket.receive(receivePacket); final String message = new String(receivePacket.getData()); if (message.contains("Belkin")) { logger.trace("Received message: {}", message); } new Thread(new Runnable() { @Override public void run() { if (message != null) { String location = StringUtils.substringBetween(message, "LOCATION: ", "/setup.xml"); String udn = StringUtils.substringBetween(message, "USN: uuid:", "::urn:Belkin"); if (udn != null) { logger.trace("Save location '{}' for WeMo device with UDN '{}'", location, udn); wemoConfigMap.put(udn, location); logger.info("Wemo Device with UDN '{}' discovered", udn); } } } }).start(); } catch (SocketTimeoutException e) { logger.debug("Message receive timed out."); for (String name : wemoConfigMap.keySet()) { logger.trace(name + ":" + wemoConfigMap.get(name)); } break; } } } finally { if (wemoReceiveSocket != null) { wemoReceiveSocket.disconnect(); wemoReceiveSocket.close(); } } } catch (Exception e) { logger.error("Could not start wemo device discovery", e); } }
From source file:org.springframework.integration.ip.udp.DatagramPacketMulticastSendingHandlerTests.java
@Test public void verifySendMulticastWithAcks() throws Exception { MulticastSocket socket;/*w ww . java 2 s. c o m*/ try { socket = new MulticastSocket(); } catch (Exception e) { return; } final int testPort = socket.getLocalPort(); final AtomicInteger ackPort = new AtomicInteger(); final String multicastAddress = "225.6.7.8"; final String payload = "foobar"; final CountDownLatch listening = new CountDownLatch(2); final CountDownLatch ackListening = new CountDownLatch(1); final CountDownLatch ackSent = new CountDownLatch(2); Runnable catcher = () -> { try { byte[] buffer = new byte[1000]; DatagramPacket receivedPacket = new DatagramPacket(buffer, buffer.length); MulticastSocket socket1 = new MulticastSocket(testPort); socket1.setInterface(InetAddress.getByName(multicastRule.getNic())); socket1.setSoTimeout(8000); InetAddress group = InetAddress.getByName(multicastAddress); socket1.joinGroup(group); listening.countDown(); assertTrue(ackListening.await(10, TimeUnit.SECONDS)); LogFactory.getLog(getClass()).debug(Thread.currentThread().getName() + " waiting for packet"); socket1.receive(receivedPacket); socket1.close(); 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)); LogFactory.getLog(getClass()).debug(Thread.currentThread().getName() + " received packet"); 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(multicastRule.getNic(), ackPort.get())); DatagramSocket out = new DatagramSocket(); out.send(ackPack); LogFactory.getLog(getClass()) .debug(Thread.currentThread().getName() + " sent ack to " + ackPack.getSocketAddress()); out.close(); ackSent.countDown(); socket1.close(); } catch (Exception e) { listening.countDown(); e.printStackTrace(); } }; Executor executor = Executors.newFixedThreadPool(2); executor.execute(catcher); executor.execute(catcher); assertTrue(listening.await(10000, TimeUnit.MILLISECONDS)); MulticastSendingMessageHandler handler = new MulticastSendingMessageHandler(multicastAddress, testPort, true, true, "localhost", 0, 10000); handler.setLocalAddress(this.multicastRule.getNic()); handler.setMinAcksForSuccess(2); handler.setBeanFactory(mock(BeanFactory.class)); handler.afterPropertiesSet(); handler.start(); waitAckListening(handler); ackPort.set(handler.getAckPort()); ackListening.countDown(); handler.handleMessage(MessageBuilder.withPayload(payload).build()); assertTrue(ackSent.await(10000, TimeUnit.MILLISECONDS)); handler.stop(); socket.close(); }