List of usage examples for java.net MulticastSocket MulticastSocket
public MulticastSocket(SocketAddress bindaddr) throws IOException
From source file:org.fourthline.cling.android.alternate.AndroidUpnpServiceConfiguration.java
@Override public DatagramIO createDatagramIO(NetworkAddressFactory networkAddressFactory) { return new DatagramIOImpl(new DatagramIOConfigurationImpl()) { @Override// w w w. j a v a 2 s .c om synchronized public void init(InetAddress bindAddress, Router router, DatagramProcessor datagramProcessor) throws InitializationException { this.router = router; this.datagramProcessor = datagramProcessor; try { // don't bind to passed bindAddress to avoid reverse DNS lookup log.info("Creating bound socket (for datagram input/output) on: " + bindAddress.getHostAddress()); localAddress = new InetSocketAddress(0); socket = new MulticastSocket(localAddress); socket.setTimeToLive(configuration.getTimeToLive()); socket.setReceiveBufferSize(262144); // Keep a backlog of incoming datagrams if we are not fast enough } catch (Exception ex) { throw new InitializationException( "Could not initialize " + getClass().getSimpleName() + ": " + ex); } } }; }
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 w w w. ja v a2 s . c o m 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:com.google.appinventor.components.runtime.BlockyTalky.java
/** * Creates a new BlockyTalky component./*w w w .j a va 2 s . co m*/ */ public BlockyTalky(ComponentContainer container) { super(container.$form()); androidUIHandler = new Handler(); localBTs = new ConcurrentHashMap<String, LocalBTData>(); headers = new HashMap<String, String>() { { put("Sec-WebSocket-Protocol", "echo-protocol"); } }; handler = new Handler(); announcerHandler = new Handler(); Log.d(LOG_TAG, "Done with BlockyTalky constructor."); String addr = getIPAddress(true); if (addr.equals("")) { addr = getIPAddress(false); } try { mContext = container.$context(); InetAddress ip = InetAddress.getByName(addr); //Android ip InetAddress bip = InetAddress.getByName(MULTICAST_ADDRESS); ds = new DatagramSocket(UNICAST_PORT); //ds.setReuseAddress(true); broadcastSocket = new MulticastSocket(MULTICAST_PORT); broadcastSocket.joinGroup(bip); broadcastSocket.setBroadcast(true); MessageListener listener = new MessageListener(); Thread listenerThread = new Thread(listener); listenerThread.start(); BroadcastListener broadcastListener = new BroadcastListener(); Thread broadcastThread = new Thread(broadcastListener); broadcastThread.start(); aquireMulticastLock(); BroadcastAnnouncer announcer = new BroadcastAnnouncer(); Thread announcerThread = new Thread(announcer); announcerThread.start(); } catch (SocketException e) { Log.d(LOG_TAG, "Caught SocketException while trying to initialize BlockyTalky messaging: " + e.getMessage()); e.printStackTrace(); } catch (UnknownHostException e) { Log.d(LOG_TAG, "Caught UnknownHostException while trying to reach Blockytalky messaging router: " + e.getMessage()); } catch (Exception e) { Log.d(LOG_TAG, "Exception while initializing BlockyTalky messaging: " + e); e.printStackTrace(); } connectToMessagingRouter(); }
From source file:com.iiitd.networking.UDPMessenger.java
public void startMessageReceiver() { Runnable receiver = new Runnable() { @Override// w w w . j a va 2s. com public void run() { WifiManager wim = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); if (wim != null) { MulticastLock mcLock = wim.createMulticastLock(TAG); mcLock.acquire(); } byte[] buffer = new byte[BUFFER_SIZE]; DatagramPacket rPacket = new DatagramPacket(buffer, buffer.length); MulticastSocket rSocket; try { rSocket = new MulticastSocket(MULTICAST_PORT); } catch (IOException e) { Log.d(DEBUG_TAG, "Impossible to create a new MulticastSocket on port " + MULTICAST_PORT); e.printStackTrace(); return; } while (receiveMessages) { try { rSocket.receive(rPacket); } catch (IOException e1) { Log.d(DEBUG_TAG, "There was a problem receiving the incoming message."); e1.printStackTrace(); continue; } if (!receiveMessages) break; byte data[] = rPacket.getData(); int i; for (i = 0; i < data.length; i++) { if (data[i] == '\0') break; } String messageText; try { messageText = new String(data, 0, i, "UTF-8"); } catch (UnsupportedEncodingException e) { Log.d(DEBUG_TAG, "UTF-8 encoding is not supported. Can't receive the incoming message."); e.printStackTrace(); continue; } try { incomingMessage = new Message(messageText, rPacket.getAddress()); } catch (IllegalArgumentException ex) { Log.d(DEBUG_TAG, "There was a problem processing the message: " + messageText); ex.printStackTrace(); continue; } incomingMessageHandler.post(getIncomingMessageAnalyseRunnable()); } } }; receiveMessages = true; if (receiverThread == null) receiverThread = new Thread(receiver); if (!receiverThread.isAlive()) receiverThread.start(); }
From source file:org.eclipse.smarthome.binding.wemo.discovery.WemoDiscoveryService.java
public void sendWemoDiscoveryMessage() { logger.debug("wemoDiscovery() is called!"); try {//from w w w. j a v a 2s. com InetAddress localhost = InetAddress.getLocalHost(); InetSocketAddress srcAddress = new InetSocketAddress(localhost, SSDP_SEARCH_PORT); 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("ST: upnp:rootdevice\r\n"); discoveryMessage.append("MAN: \"ssdp:discover\"\r\n"); discoveryMessage.append("MX: 5\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(4); logger.debug("Send multicast request."); multicast.send(discoveryPacket); } finally { logger.trace("Multicast ends. Close connection."); multicast.disconnect(); multicast.close(); } // Response-Listener DatagramSocket wemoReceiveSocket = null; DatagramPacket receivePacket = null; try { wemoReceiveSocket = new DatagramSocket(SSDP_SEARCH_PORT); wemoReceiveSocket.setSoTimeout(TIMEOUT); logger.debug("Send datagram packet."); wemoReceiveSocket.send(discoveryPacket); while (true) { try { receivePacket = new DatagramPacket(new byte[1536], 1536); wemoReceiveSocket.receive(receivePacket); final String message = new String(receivePacket.getData()); logger.trace("Received message: {}", message); new Thread(new Runnable() { @Override public void run() { String label = "WeMo Device"; String wemoUDN = null; String wemoLocation = null; String wemoFriendlyName = null; String wemoModelName = null; ThingUID uid = null; if (message != null) { if (message.contains("Socket-1_0") || message.contains("Insight-1_0") || message.contains("Motion-1_0") || message.contains("Lightswitch-1_0")) { wemoUDN = StringUtils.substringBetween(message, "USN: uuid:", "::upnp:rootdevice"); logger.debug("Wemo device with UDN '{}' found", wemoUDN); wemoLocation = StringUtils.substringBetween(message, "LOCATION: ", "/setup.xml"); if (wemoLocation != null) { try { int timeout = 5000; String response = HttpUtil.executeUrl("GET", wemoLocation + "/setup.xml", timeout); wemoFriendlyName = StringUtils.substringBetween(response, "<friendlyName>", "</friendlyName>"); logger.debug("Wemo device '{}' found at '{}'", wemoFriendlyName, wemoLocation); wemoModelName = StringUtils.substringBetween(response, "<modelName>", "</modelName>"); logger.trace("Wemo device '{}' has model name '{}'", wemoFriendlyName, wemoModelName); label = "Wemo" + wemoModelName; switch (wemoModelName) { case "Socket": logger.debug( "Creating ThingUID for device model '{}' with UDN '{}'", wemoModelName, wemoUDN); uid = new ThingUID(WEMO_SOCKET_TYPE_UID, wemoUDN); break; case "Insight": logger.trace( "Creating ThingUID for device model '{}' with UDN '{}'", wemoModelName, wemoUDN); uid = new ThingUID(WEMO_INSIGHT_TYPE_UID, wemoUDN); break; case "LightSwitch": logger.trace( "Creating ThingUID for device model '{}' with UDN '{}'", wemoModelName, wemoUDN); uid = new ThingUID(WEMO_LIGHTSWITCH_TYPE_UID, wemoUDN); break; case "Motion": logger.trace( "Creating ThingUID for device model '{}' with UDN '{}'", wemoModelName, wemoUDN); uid = new ThingUID(WEMO_MOTION_TYPE_UID, wemoUDN); break; } Map<String, Object> properties = new HashMap<>(4); properties.put(UDN, wemoUDN); properties.put(LOCATION, wemoLocation); DiscoveryResult result = DiscoveryResultBuilder.create(uid) .withProperties(properties).withLabel(label).build(); thingDiscovered(result); } catch (Exception te) { logger.error("Could not discover WeMo device", te); } } } } } }).start(); } catch (SocketTimeoutException e) { logger.debug("Message receive timed out."); break; } } } finally { if (wemoReceiveSocket != null) { wemoReceiveSocket.disconnect(); wemoReceiveSocket.close(); } } } catch (Exception e) { logger.error("Could not send Wemo device discovery", e); } }
From source file:org.springframework.integration.ip.udp.DatagramPacketSendingHandlerTests.java
@Test @Ignore//from w w w . j a v a 2 s . c o m public void verifySendMulticast() throws Exception { final int testPort = SocketUtils.findAvailableUdpSocket(); final String multicastAddress = "225.6.7.8"; final String payload = "foo"; final CountDownLatch latch1 = new CountDownLatch(2); final CountDownLatch latch2 = new CountDownLatch(2); Runnable catcher = new Runnable() { public void run() { try { byte[] buffer = new byte[8]; DatagramPacket receivedPacket = new DatagramPacket(buffer, buffer.length); MulticastSocket socket = new MulticastSocket(testPort); InetAddress group = InetAddress.getByName(multicastAddress); socket.joinGroup(group); latch1.countDown(); LogFactory.getLog(getClass()).debug(Thread.currentThread().getName() + " waiting for packet"); socket.receive(receivedPacket); socket.close(); byte[] src = receivedPacket.getData(); int length = receivedPacket.getLength(); int offset = receivedPacket.getOffset(); byte[] dest = new byte[length]; System.arraycopy(src, offset, dest, 0, length); assertEquals(payload, new String(dest)); LogFactory.getLog(getClass()).debug(Thread.currentThread().getName() + " received packet"); latch2.countDown(); } catch (Exception e) { noMulticast = true; latch1.countDown(); e.printStackTrace(); } } }; Executor executor = Executors.newFixedThreadPool(2); executor.execute(catcher); executor.execute(catcher); latch1.await(3000, TimeUnit.MILLISECONDS); if (noMulticast) { return; } MulticastSendingMessageHandler handler = new MulticastSendingMessageHandler(multicastAddress, testPort); handler.handleMessage(MessageBuilder.withPayload(payload).build()); assertTrue(latch2.await(3000, TimeUnit.MILLISECONDS)); handler.shutDown(); }
From source file:org.apache.catalina.cluster.mcast.McastServiceImpl.java
/** * Create a new mcast service impl//from www . j a va2 s .co m * @param member - the local member * @param sendFrequency - the time (ms) in between pings sent out * @param expireTime - the time (ms) for a member to expire * @param port - the mcast port * @param bind - the bind address (not sure this is used yet) * @param mcastAddress - the mcast address * @param service - the callback service * @throws IOException */ public McastServiceImpl(McastMember member, long sendFrequency, long expireTime, int port, InetAddress bind, InetAddress mcastAddress, MembershipListener service) throws IOException { if (bind != null) socket = new MulticastSocket(new java.net.InetSocketAddress(bind, port)); else socket = new MulticastSocket(port); this.member = member; address = mcastAddress; this.port = port; sendPacket = new DatagramPacket(new byte[1000], 1000); sendPacket.setAddress(address); sendPacket.setPort(port); receivePacket = new DatagramPacket(new byte[1000], 1000); receivePacket.setAddress(address); receivePacket.setPort(port); membership = new McastMembership(member.getName()); timeToExpiration = expireTime; this.service = service; this.sendFrequency = sendFrequency; }
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. *//*from w ww .j av a2 s.c om*/ 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:net.pms.network.UPNPHelper.java
/** * Gets the new multicast socket./*ww w . java2s.c o m*/ * * @return the new multicast socket * @throws IOException Signals that an I/O exception has occurred. */ private static MulticastSocket getNewMulticastSocket() throws IOException { NetworkInterface networkInterface = NetworkConfiguration.getInstance().getNetworkInterfaceByServerName(); if (networkInterface == null) { networkInterface = PMS.get().getServer().getNetworkInterface(); } if (networkInterface == null) { throw new IOException("No usable network interface found for UPnP multicast"); } List<InetAddress> usableAddresses = new ArrayList<InetAddress>(); List<InetAddress> networkInterfaceAddresses = Collections.list(networkInterface.getInetAddresses()); for (InetAddress inetAddress : networkInterfaceAddresses) { if (inetAddress != null && inetAddress instanceof Inet4Address && !inetAddress.isLoopbackAddress()) { usableAddresses.add(inetAddress); } } if (usableAddresses.isEmpty()) { throw new IOException("No usable addresses found for UPnP multicast"); } InetSocketAddress localAddress = new InetSocketAddress(usableAddresses.get(0), 0); MulticastSocket ssdpSocket = new MulticastSocket(localAddress); ssdpSocket.setReuseAddress(true); logger.trace( "Sending message from multicast socket on network interface: " + ssdpSocket.getNetworkInterface()); logger.trace("Multicast socket is on interface: " + ssdpSocket.getInterface()); ssdpSocket.setTimeToLive(32); logger.trace("Socket Timeout: " + ssdpSocket.getSoTimeout()); logger.trace("Socket TTL: " + ssdpSocket.getTimeToLive()); return ssdpSocket; }
From source file:org.springframework.integration.ip.udp.DatagramPacketSendingHandlerTests.java
@Test @Ignore/*from w w w. j a v a2 s . c o m*/ public void verifySendMulticastWithAcks() throws Exception { final List<Integer> openPorts = SocketUtils.findAvailableUdpSockets(SocketUtils.getRandomSeedPort(), 2); final int testPort = openPorts.get(0); final int ackPort = openPorts.get(1); final String multicastAddress = "225.6.7.8"; final String payload = "foobar"; final CountDownLatch latch1 = new CountDownLatch(2); final CountDownLatch latch2 = new CountDownLatch(2); Runnable catcher = new Runnable() { public void run() { try { byte[] buffer = new byte[1000]; DatagramPacket receivedPacket = new DatagramPacket(buffer, buffer.length); MulticastSocket socket = new MulticastSocket(testPort); InetAddress group = InetAddress.getByName(multicastAddress); socket.joinGroup(group); latch1.countDown(); LogFactory.getLog(getClass()).debug(Thread.currentThread().getName() + " waiting for packet"); socket.receive(receivedPacket); socket.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("localHost", ackPort)); DatagramSocket out = new DatagramSocket(); out.send(ackPack); out.close(); latch2.countDown(); } catch (Exception e) { noMulticast = true; latch1.countDown(); e.printStackTrace(); } } }; Executor executor = Executors.newFixedThreadPool(2); executor.execute(catcher); executor.execute(catcher); latch1.await(3000, TimeUnit.MILLISECONDS); if (noMulticast) { return; } MulticastSendingMessageHandler handler = new MulticastSendingMessageHandler(multicastAddress, testPort, true, true, "localhost", ackPort, 500000); handler.setMinAcksForSuccess(2); handler.handleMessage(MessageBuilder.withPayload(payload).build()); assertTrue(latch2.await(10000, TimeUnit.MILLISECONDS)); handler.shutDown(); }