List of usage examples for java.net MulticastSocket receive
public synchronized void receive(DatagramPacket p) throws IOException
From source file:Main.java
public static void main(String[] argv) throws Exception { MulticastSocket msocket = new MulticastSocket(9999); byte[] inbuf = new byte[1024]; DatagramPacket packet = new DatagramPacket(inbuf, inbuf.length); msocket.receive(packet); // Data is now in inbuf int numBytesReceived = packet.getLength(); }
From source file:MulticastSniffer.java
public static void main(String[] args) { InetAddress ia = null;//from ww w . ja v a 2 s.co m byte[] buffer = new byte[65509]; DatagramPacket dp = new DatagramPacket(buffer, buffer.length); int port = 0; try { try { ia = InetAddress.getByName(args[0]); } catch (UnknownHostException e) { // } port = Integer.parseInt(args[1]); } // end try catch (Exception e) { System.err.println(e); System.err.println("Usage: java MulticastSniffer MulticastAddress port"); System.exit(1); } try { MulticastSocket ms = new MulticastSocket(port); ms.joinGroup(ia); while (true) { ms.receive(dp); String s = new String(dp.getData(), 0, 0, dp.getLength()); System.out.println(s); } } catch (SocketException se) { System.err.println(se); } catch (IOException ie) { System.err.println(ie); } }
From source file:MulticastSniffer.java
public static void main(String[] args) { InetAddress ia = null;// ww w.j ava 2s .c o m byte[] buffer = new byte[65535]; DatagramPacket dp = new DatagramPacket(buffer, buffer.length); int port = 0; // read the address from the command line try { try { ia = InetAddress.getByName(args[0]); } catch (UnknownHostException e) { System.err.println(e); } port = Integer.parseInt(args[1]); } catch (Exception e) { System.err.println(e); System.err.println("Usage: java MulticastSniffer mcast-addr port"); System.exit(1); } System.out.println("About to join " + ia); try { MulticastSocket ms = new MulticastSocket(port); ms.joinGroup(ia); while (true) { System.out.println("About to receive..."); ms.receive(dp); String s = new String(dp.getData(), 0, 0, dp.getLength()); System.out.println(s); } } catch (SocketException se) { System.err.println(se); } catch (IOException ie) { System.err.println(ie); } }
From source file:MainClass.java
public static void main(String[] args) throws Exception { int port = 0; InetAddress group = InetAddress.getByName("127.0.0.1"); MulticastSocket ms = new MulticastSocket(port); ms.joinGroup(group);// w ww . j a va2 s . co m byte[] buffer = new byte[8192]; while (true) { DatagramPacket dp = new DatagramPacket(buffer, buffer.length); ms.receive(dp); String s = new String(dp.getData()); System.out.println(s); } // ms.leaveGroup(group); // ms.close(); }
From source file:Main.java
public static void main(String[] args) throws Exception { int mcPort = 12345; String mcIPStr = "230.1.1.1"; MulticastSocket mcSocket = null; InetAddress mcIPAddress = null; mcIPAddress = InetAddress.getByName(mcIPStr); mcSocket = new MulticastSocket(mcPort); System.out.println("Multicast Receiver running at:" + mcSocket.getLocalSocketAddress()); mcSocket.joinGroup(mcIPAddress);// www . j av a 2 s . c om DatagramPacket packet = new DatagramPacket(new byte[1024], 1024); System.out.println("Waiting for a multicast message..."); mcSocket.receive(packet); String msg = new String(packet.getData(), packet.getOffset(), packet.getLength()); System.out.println("[Multicast Receiver] Received:" + msg); mcSocket.leaveGroup(mcIPAddress); mcSocket.close(); }
From source file:MulticastClient.java
public static void main(String[] args) throws IOException { MulticastSocket socket = new MulticastSocket(4446); InetAddress address = InetAddress.getByName("230.0.0.1"); socket.joinGroup(address);// ww w .ja va2s.c o m DatagramPacket packet; // get a few quotes for (int i = 0; i < 5; i++) { byte[] buf = new byte[256]; packet = new DatagramPacket(buf, buf.length); socket.receive(packet); String received = new String(packet.getData()); System.out.println("Quote of the Moment: " + received); } socket.leaveGroup(address); socket.close(); }
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 va 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:com.iiitd.networking.UDPMessenger.java
public void startMessageReceiver() { Runnable receiver = new Runnable() { @Override// ww w . ja v a 2 s. 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: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 . j a va 2 s.co 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:net.pms.network.UPNPHelper.java
/** * Starts up two threads: one to broadcast UPnP ALIVE messages and another * to listen for responses. /*from ww w . jav a2 s. 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(); }