List of usage examples for java.net MulticastSocket MulticastSocket
public MulticastSocket(SocketAddress bindaddr) throws IOException
From source file:org.openhab.binding.wemo.internal.WemoBinding.java
public void wemoDiscovery() { logger.debug("wemoDiscovery() is called!"); try {/* www. jav a2s . c o m*/ 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:net.pms.network.UPNPHelper.java
/** * Starts up two threads: one to broadcast UPnP ALIVE messages and another * to listen for responses. //from w ww . ja va 2s . c o m * * @throws IOException Signals that an I/O exception has occurred. */ public static void listen() throws IOException { Runnable rAlive = new Runnable() { @Override public void run() { int delay = 10000; while (true) { sleep(delay); sendAlive(); // The first delay for sending an ALIVE message is 10 seconds, // the second delay is for 20 seconds. From then on, all other // delays are for 180 seconds. switch (delay) { case 10000: delay = 20000; break; case 20000: delay = 180000; break; } } } }; aliveThread = new Thread(rAlive, "UPNP-AliveMessageSender"); aliveThread.start(); Runnable r = new Runnable() { @Override public void run() { boolean bindErrorReported = false; while (true) { MulticastSocket multicastSocket = null; try { // Use configurable source port as per http://code.google.com/p/ps3mediaserver/issues/detail?id=1166 multicastSocket = new MulticastSocket(configuration.getUpnpPort()); if (bindErrorReported) { logger.warn( "Finally, acquiring port " + configuration.getUpnpPort() + " was successful!"); } NetworkInterface ni = NetworkConfiguration.getInstance().getNetworkInterfaceByServerName(); try { // Setting the network interface will throw a SocketException on Mac OSX // with Java 1.6.0_45 or higher, but if we don't do it some Windows // configurations will not listen at all. if (ni != null) { multicastSocket.setNetworkInterface(ni); } else if (PMS.get().getServer().getNetworkInterface() != null) { multicastSocket.setNetworkInterface(PMS.get().getServer().getNetworkInterface()); logger.trace("Setting multicast network interface: " + PMS.get().getServer().getNetworkInterface()); } } catch (SocketException e) { // Not setting the network interface will work just fine on Mac OSX. } multicastSocket.setTimeToLive(4); multicastSocket.setReuseAddress(true); InetAddress upnpAddress = getUPNPAddress(); multicastSocket.joinGroup(upnpAddress); while (true) { byte[] buf = new byte[1024]; DatagramPacket receivePacket = new DatagramPacket(buf, buf.length); multicastSocket.receive(receivePacket); String s = new String(receivePacket.getData()); InetAddress address = receivePacket.getAddress(); if (s.startsWith("M-SEARCH")) { String remoteAddr = address.getHostAddress(); int remotePort = receivePacket.getPort(); if (configuration.getIpFiltering().allowed(address)) { logger.trace( "Receiving a M-SEARCH from [" + remoteAddr + ":" + remotePort + "]"); if (StringUtils.indexOf(s, "urn:schemas-upnp-org:service:ContentDirectory:1") > 0) { sendDiscover(remoteAddr, remotePort, "urn:schemas-upnp-org:service:ContentDirectory:1"); } if (StringUtils.indexOf(s, "upnp:rootdevice") > 0) { sendDiscover(remoteAddr, remotePort, "upnp:rootdevice"); } if (StringUtils.indexOf(s, "urn:schemas-upnp-org:device:MediaServer:1") > 0) { sendDiscover(remoteAddr, remotePort, "urn:schemas-upnp-org:device:MediaServer:1"); } if (StringUtils.indexOf(s, "ssdp:all") > 0) { sendDiscover(remoteAddr, remotePort, "urn:schemas-upnp-org:device:MediaServer:1"); } if (StringUtils.indexOf(s, PMS.get().usn()) > 0) { sendDiscover(remoteAddr, remotePort, PMS.get().usn()); } } } else if (s.startsWith("NOTIFY")) { String remoteAddr = address.getHostAddress(); int remotePort = receivePacket.getPort(); logger.trace("Receiving a NOTIFY from [" + remoteAddr + ":" + remotePort + "]"); } } } catch (BindException e) { if (!bindErrorReported) { logger.error("Unable to bind to " + configuration.getUpnpPort() + ", which means that PMS will not automatically appear on your renderer! " + "This usually means that another program occupies the port. Please " + "stop the other program and free up the port. " + "PMS will keep trying to bind to it...[" + e.getMessage() + "]"); } bindErrorReported = true; sleep(5000); } catch (IOException e) { logger.error("UPNP network exception", e); sleep(1000); } finally { if (multicastSocket != null) { // Clean up the multicast socket nicely try { InetAddress upnpAddress = getUPNPAddress(); multicastSocket.leaveGroup(upnpAddress); } catch (IOException e) { } multicastSocket.disconnect(); multicastSocket.close(); } } } } }; listenerThread = new Thread(r, "UPNPHelper"); listenerThread.start(); }
From source file:com.all.landownloader.discovery.LanDiscoverySocket.java
public LanDiscoveredPeer listen() throws IOException, IllegalArgumentException { MulticastSocket socket = new MulticastSocket(PORT); socket.joinGroup(addressGroup);//from w w w . ja v a 2 s. c o m byte[] buf = new byte[BUF_LENGTH]; DatagramPacket packet = new DatagramPacket(buf, buf.length); socket.receive(packet); socket.leaveGroup(addressGroup); socket.close(); InetAddress address = packet.getAddress(); byte[] remotePortBuffer = new byte[4]; System.arraycopy(buf, HEADER_LENGTH, remotePortBuffer, 0, remotePortBuffer.length); LanDiscoveredPeer discoveredPeer = new LanDiscoveredPeer(address, LanUtils.decodeInt(remotePortBuffer)); if (eq(BYE_MSG, buf, HEADER_LENGTH)) { addresses.remove(address); RegisteredAddress remove = quickLeases.remove(address); if (remove != null) { leases.remove(remove); } return null; } RegisteredAddress reg = quickLeases.get(discoveredPeer); long nextLeaseTime = System.currentTimeMillis() + this.leaseTime; if (reg == null) { reg = new RegisteredAddress(nextLeaseTime, discoveredPeer); quickLeases.put(discoveredPeer, reg); } else { reg.setLease(nextLeaseTime); } if (eq(ANNOUNCE_MSG, buf, HEADER_LENGTH)) { reply(address); } leases.add(reg); addresses.add(discoveredPeer); return discoveredPeer; }
From source file:Reflector.java
private MulticastSocket initMulticastSocket() { // initialize a MulticastSocket MulticastSocket mc;//from w w w.ja v a 2 s.co m try { mc = new MulticastSocket(sendPort); } catch (Exception e) { e.printStackTrace(); return (null); } return (mc); }
From source file:Reflector.java
private MulticastSocket initMulticastSocket() { // initialize a MulticastSocket and join the group MulticastSocket mc;/*from www. j av a 2s. c om*/ try { mc = new MulticastSocket(listenPort); mc.joinGroup(listenAddr); } catch (Exception e) { System.err.println("Failed to create MulticastSocket on " + "port " + listenPort); return (null); } return (mc); }