@Override protected void onResume() { super.onResume(); fileReciveThread = new FileReciveThread(); fileReciveThread.start(); try { socket = new MulticastSocket(portNum); socket.setInterface(ip); socket.setBroadcast(true); group = InetAddress.getByName("224.0.0.1"); socket.joinGroup(new InetSocketAddress(group, portNum), networkInterface); } catch (IOException e) { e.printStackTrace(); } }
public PacketReceiver( MessageListener listener ) { messageListener = listener; // set MessageListener try // connect MulticastSocket to multicast address and port { // create new MulticastSocket multicastSocket = new MulticastSocket( MULTICAST_LISTENING_PORT ); // use InetAddress to get multicast group multicastGroup = InetAddress.getByName( MULTICAST_ADDRESS ); // join multicast group to receive messages multicastSocket.joinGroup( multicastGroup ); // set 5 second timeout when waiting for new packets multicastSocket.setSoTimeout( 5000 ); } // end try catch ( IOException ioException ) { ioException.printStackTrace(); } // end catch }
/** * This RTP socket implements a buffering mechanism relying on a FIFO of buffers and a Thread. */ public RtpSocketUdp(ConnectCheckerRtsp connectCheckerRtsp) { super(); this.connectCheckerRtsp = connectCheckerRtsp; senderReportUdp = new SenderReportUdp(connectCheckerRtsp); senderReportUdp.reset(); packets = new DatagramPacket[bufferCount]; for (int i = 0; i < bufferCount; i++) { packets[i] = new DatagramPacket(buffers[i], 1); } try { mSocket = new MulticastSocket(); } catch (IOException e) { e.printStackTrace(); } }
public RTPSocketAdapter(InetAddress addr, int port, int ttl) throws IOException { try { if (addr.isMulticastAddress()) { dataSock = new MulticastSocket(port); ctrlSock = new MulticastSocket(port+1); ((MulticastSocket)dataSock).joinGroup(addr); ((MulticastSocket)dataSock).setTimeToLive(ttl); ((MulticastSocket)ctrlSock).joinGroup(addr); ((MulticastSocket)ctrlSock).setTimeToLive(ttl); } else { dataSock = new DatagramSocket(port, InetAddress.getLocalHost()); ctrlSock = new DatagramSocket(port+1, InetAddress.getLocalHost()); } } catch (SocketException e) { throw new IOException(e.getMessage()); } this.addr = addr; this.port = port; }
UDPread0(int iport, String isrcName, String[] ichanName, int idt) { port = iport; srcName = isrcName; chanName = ichanName; try { //open port for incoming UDP if(multiCast != null) { System.err.println("Multicast address: "+multiCast); ms = new MulticastSocket(port); ms.joinGroup(InetAddress.getByName(multiCast)); } else { ds = new DatagramSocket(port); // ds.setSoTimeout(10); // non-blocking timeout } } catch (Exception e) { e.printStackTrace(); } }
/** * * @param multicastIP for example, 224.X.X.X or 239.X.X.X * @param port * @param bs */ public static void multicast(final String multicastIP, final int port, final byte[] sendData){ final WifiManager wifi = getWiFiManager(); MulticastLock multicastLock = wifi.createMulticastLock(String.valueOf(System.currentTimeMillis())); multicastLock.setReferenceCounted(true); multicastLock.acquire(); try{ final MulticastSocket multicastSocket=new MulticastSocket(port); multicastSocket.setLoopbackMode(true); final InetAddress group = InetAddress.getByName(multicastIP); multicastSocket.joinGroup(group); final DatagramPacket packet=new DatagramPacket(sendData, sendData.length,group,port); multicastSocket.send(packet); }catch (final Throwable e) { e.printStackTrace(); } if (multicastLock != null) { multicastLock.release(); multicastLock = null; } }
/** * Send an outgoing multicast DNS message. * * @param out * @exception IOException */ public void send(DNSOutgoing out) throws IOException { if (!out.isEmpty()) { byte[] message = out.data(); final DatagramPacket packet = new DatagramPacket(message, message.length, _group, DNSConstants.MDNS_PORT); if (logger.isLoggable(Level.FINEST)) { try { final DNSIncoming msg = new DNSIncoming(packet); if (logger.isLoggable(Level.FINEST)) { logger.finest("send(" + this.getName() + ") JmDNS out:" + msg.print(true)); } } catch (final IOException e) { logger.throwing(getClass().toString(), "send(" + this.getName() + ") - JmDNS can not parse what it sends!!!", e); } } final MulticastSocket ms = _socket; if (ms != null && !ms.isClosed()) { ms.send(packet); } } }
@Test public void sendTextMessageThroughUdp() throws Exception { // replace existing implementation for testing purposes _testKit.removeService("DefaultGreetingService"); final MockHandler greetingService = _testKit.registerInOnlyService("DefaultGreetingService"); MulticastSocket clientSocket = new MulticastSocket(); InetAddress group = InetAddress.getByName("localhost"); byte[] datagramBody = PAYLOAD.getBytes(Charset.defaultCharset()); DatagramPacket packet = new DatagramPacket(datagramBody, 0, datagramBody.length, group, 3940); clientSocket.send(packet); // sleep a bit to receive message on camel side clientSocket.close(); greetingService.waitForOKMessage(); final LinkedBlockingQueue<Exchange> recievedMessages = greetingService.getMessages(); assertThat(recievedMessages, is(notNullValue())); final Exchange recievedExchange = recievedMessages.iterator().next(); String content = recievedExchange.getMessage().getContent(String.class); // the receive content is trimmed because extra bytes appended to frame by receiver assertThat(PAYLOAD, is(equalTo(content.trim()))); }
public void sendFrame(final Frame frame) throws IOException { final byte[] message = toValidMessage(frame); final DatagramPacket packet = new DatagramPacket(message, 0, message.length, mcastAddress, mcastPort); for (final MulticastSocket mcastSocket : mcastSockets) { try { sentMessages++; mcastSocket.send(packet); } catch (final IOException e) { final String exceptionMessage = e.getMessage(); if (exceptionMessage.endsWith(NO_BUFFER_SPACE_AVAILABLE) || exceptionMessage.endsWith(NO_ROUTE_TO_HOST)) { final NetworkInterface networkInterface = mcastSocket.getNetworkInterface(); final InetAddress mcastSocketInterface = mcastSocket.getInterface(); LOG.warn(createIgnoredWarning(exceptionMessage, networkInterface, mcastSocketInterface)); } else { throw e; } } } }
/** * Broadcasts a SSDP discovery message into the network to find provided * services. * * @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; }
/** * 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); }
static String retrieveResponse() throws Exception { String response = null; MulticastSocket recSocket = setUpSocket(); int i = 0; while (response == null) { byte[] buf = new byte[2048]; DatagramPacket input = new DatagramPacket(buf, buf.length); try { recSocket.receive(input); response = new String(input.getData()); } catch (SocketTimeoutException e) { if (i >= 10) break; i++; } } return response; }
/** * This RTP socket implements a buffering mechanism relying on a FIFO of buffers and a Thread. * @throws IOException */ public RtpSocket() { mCacheSize = 0; mBufferQ = new ConcurrentLinkedQueue<PacketBufferClass>(); mReport = new SenderReport(); mAverageBitrate = new AverageBitrate(); mTransport = TRANSPORT_UDP; mTcpHeader = new byte[] {'$',0,0,0}; mBufferInOut = new AtomicInteger(); mPayloadType = 96; resetFifo(); try { mSocket = new MulticastSocket(); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } }
/** * Creates multicast socket and joins multicast group. * * @throws IOException If fails to create socket or join multicast group. * @return Multicast socket. */ private MulticastSocket createSocket() throws IOException { MulticastSocket sock = new MulticastSocket(mcastPort); sock.setLoopbackMode(false); // Use 'false' to enable support for more than one node on the same machine. if (sockItf != null) sock.setInterface(sockItf); if (sock.getLoopbackMode()) U.warn(log, "Loopback mode is disabled which prevents nodes on the same machine from discovering " + "each other."); sock.joinGroup(mcastGrp); if (ttl != -1) sock.setTimeToLive(ttl); return sock; }
synchronized public void init(InetAddress bindAddress, Router router, DatagramProcessor datagramProcessor) throws InitializationException { this.router = router; this.datagramProcessor = datagramProcessor; try { // TODO: UPNP VIOLATION: The spec does not prohibit using the 1900 port here again, however, the // Netgear ReadyNAS miniDLNA implementation will no longer answer if it has to send search response // back via UDP unicast to port 1900... so we use an ephemeral port log.info("Creating bound socket (for datagram input/output) on: " + bindAddress); localAddress = new InetSocketAddress(bindAddress, 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); } }
synchronized public void init(NetworkInterface networkInterface, Router router, NetworkAddressFactory networkAddressFactory, DatagramProcessor datagramProcessor) throws InitializationException { this.router = router; this.networkAddressFactory = networkAddressFactory; this.datagramProcessor = datagramProcessor; this.multicastInterface = networkInterface; try { log.info("Creating wildcard socket (for receiving multicast datagrams) on port: " + configuration.getPort()); multicastAddress = new InetSocketAddress(configuration.getGroup(), configuration.getPort()); socket = new MulticastSocket(configuration.getPort()); socket.setReuseAddress(true); socket.setReceiveBufferSize(32768); // Keep a backlog of incoming datagrams if we are not fast enough log.info("Joining multicast group: " + multicastAddress + " on network interface: " + multicastInterface.getDisplayName()); socket.joinGroup(multicastAddress, multicastInterface); } catch (Exception ex) { throw new InitializationException("Could not initialize " + getClass().getSimpleName() + ": " + ex); } }
public RxdThread() { super("MultiCastManager.RxdThread." + address + "#" + port); setDaemon(true); bReceiving = true; try { msocket = new MulticastSocket( port ); msocket.setInterface( bindAddress ); msocket.joinGroup(groupAddr); start(); cfcThread = new cfcRunnerThread(); } catch (IOException e) { log( "RxdThread.IOException:" + e.getMessage() ); } }
@Test public void testShouldCreateDatagramSocketIfMulticastIsDisabled() throws Exception { GangliaContext context = new GangliaContext(); ContextFactory factory = ContextFactory.getFactory(); factory.setAttribute("gangliaContext.multicast", "false"); context.init("gangliaContext", factory); assertFalse("Created MulticastSocket", context.datagramSocket instanceof MulticastSocket); }
@Test public void testShouldCreateMulticastSocket() throws Exception { GangliaContext context = new GangliaContext(); ContextFactory factory = ContextFactory.getFactory(); factory.setAttribute("gangliaContext.multicast", "true"); context.init("gangliaContext", factory); assertTrue("Did not create MulticastSocket", context.datagramSocket instanceof MulticastSocket); MulticastSocket multicastSocket = (MulticastSocket) context.datagramSocket; assertEquals("Did not set default TTL", multicastSocket.getTimeToLive(), 1); }
@Test public void testShouldSetMulticastSocketTtl() throws Exception { GangliaContext context = new GangliaContext(); ContextFactory factory = ContextFactory.getFactory(); factory.setAttribute("gangliaContext.multicast", "true"); factory.setAttribute("gangliaContext.multicast.ttl", "10"); context.init("gangliaContext", factory); MulticastSocket multicastSocket = (MulticastSocket) context.datagramSocket; assertEquals("Did not set TTL", multicastSocket.getTimeToLive(), 10); }
@Test public void testShouldCreateDatagramSocketByDefault() throws Exception { SubsetConfiguration conf = new ConfigBuilder() .subset("test.sink.ganglia"); GangliaSink30 gangliaSink = new GangliaSink30(); gangliaSink.init(conf); DatagramSocket socket = gangliaSink.getDatagramSocket(); assertFalse("Did not create DatagramSocket", socket == null || socket instanceof MulticastSocket); }
@Test public void testShouldCreateDatagramSocketIfMulticastIsDisabled() throws Exception { SubsetConfiguration conf = new ConfigBuilder() .add("test.sink.ganglia.multicast", false) .subset("test.sink.ganglia"); GangliaSink30 gangliaSink = new GangliaSink30(); gangliaSink.init(conf); DatagramSocket socket = gangliaSink.getDatagramSocket(); assertFalse("Did not create DatagramSocket", socket == null || socket instanceof MulticastSocket); }
@Test public void testShouldCreateMulticastSocket() throws Exception { SubsetConfiguration conf = new ConfigBuilder() .add("test.sink.ganglia.multicast", true) .subset("test.sink.ganglia"); GangliaSink30 gangliaSink = new GangliaSink30(); gangliaSink.init(conf); DatagramSocket socket = gangliaSink.getDatagramSocket(); assertTrue("Did not create MulticastSocket", socket != null && socket instanceof MulticastSocket); int ttl = ((MulticastSocket) socket).getTimeToLive(); assertEquals("Did not set default TTL", 1, ttl); }
@Test public void testShouldSetMulticastSocketTtl() throws Exception { SubsetConfiguration conf = new ConfigBuilder() .add("test.sink.ganglia.multicast", true) .add("test.sink.ganglia.multicast.ttl", 3) .subset("test.sink.ganglia"); GangliaSink30 gangliaSink = new GangliaSink30(); gangliaSink.init(conf); DatagramSocket socket = gangliaSink.getDatagramSocket(); assertTrue("Did not create MulticastSocket", socket != null && socket instanceof MulticastSocket); int ttl = ((MulticastSocket) socket).getTimeToLive(); assertEquals("Did not set TTL", 3, ttl); }
public Socket(MainWindow main) throws UnknownHostException { this.main = main; this.address = InetAddress.getByName(Socket.INET_ADDR); try { multicastSocket = new MulticastSocket(this.main.getPort()); multicastSocket.setSendBufferSize(256000); multicastSocket.setReceiveBufferSize(256000); multicastSocket.setReuseAddress(true); multicastSocket.joinGroup(address); } catch (IOException ex) { System.out.println("There is no socket connection. Sorry."); System.out.println(ex.toString()); } }
private void safeClose(final MulticastSocket multicastSocket) { try { if (multicastSocket != null) { multicastSocket.close(); } } catch (final RuntimeException e) { if (logger.isDebugEnabled()) { logger.debug("Ignored exception while safe-closing multicast socket.", e); } } }
@Test public void testDefaultPort() { MulticastRegistry multicastRegistry = new MulticastRegistry(URL.valueOf("multicast://224.5.6.7")); try { MulticastSocket multicastSocket = multicastRegistry.getMutilcastSocket(); Assert.assertEquals(1234, multicastSocket.getLocalPort()); } finally { multicastRegistry.destroy(); } }
public DatagramSocket createDatagramSocket(int port, InetAddress laddr) throws SocketException { if ( laddr.isMulticastAddress() ) { try { MulticastSocket ds = new MulticastSocket( port ); ds.joinGroup( laddr ); return ds; } catch (IOException e) { throw new SocketException( e.getLocalizedMessage() ); } } else return new DatagramSocket(port, laddr); }
public ThreadLanServerFind(LanServerDetector.LanServerList p_i1320_1_) throws IOException { super("LanServerDetector #" + LanServerDetector.field_148551_a.incrementAndGet()); this.localServerList = p_i1320_1_; this.setDaemon(true); this.socket = new MulticastSocket(4445); this.broadcastAddress = InetAddress.getByName("224.0.2.60"); this.socket.setSoTimeout(5000); this.socket.joinGroup(this.broadcastAddress); }
public void run() { try { InetAddress multicastAddress = InetAddress.getByName(Constants.MULTICAST_ADDRESS); this.msocket = new MulticastSocket(Constants.SSDP_PORT); this.msocket.setReuseAddress(true); this.msocket.joinGroup(multicastAddress); byte[] buffer = new byte[2048]; DatagramPacket packet = new DatagramPacket(buffer, buffer.length); while (!this.terminated) { this.msocket.receive(packet); String message = new String(packet.getData(), "UTF-8"); if (message.contains("M-SEARCH")) { log.debug("Received Search Request from " + packet.getSocketAddress().toString() + ":\n" + message); if (this.checkSearch(message) && packet.getPort() == 50000) { log.info("DiscoveryResponse needed"); this.sendDiscoveryResponse(packet.getAddress(), packet.getPort()); } } // Reset the length of the packet before reusing it. packet.setLength(buffer.length); } } catch (IOException e) { log.error("Error while listening for UDP packages", e); } finally { this.msocket.close(); } }
private void init() throws IOException { ms = new MulticastSocket(advertisePort); ms.setTimeToLive(16); ms.joinGroup(InetAddress.getByName(groupAddress)); initialized = true; }
/** Constructs a new AEMulticastInput thread. This Thread must be started before it will *collect events from a source. *@throws IOException if there is a permission problem **/ public AEMulticastInput() throws IOException{ socket = new MulticastSocket(AENetworkInterfaceConstants.STREAM_PORT); address = InetAddress.getByName(AENetworkInterfaceConstants.MULTICAST_INETADDR); socket.joinGroup(address); setName("AEMulticastInput"); }
public SenderReportUdp(ConnectCheckerRtsp connectCheckerRtsp) { super(); this.connectCheckerRtsp = connectCheckerRtsp; try { socket = new MulticastSocket(); } catch (IOException e) { // Very unlikely to happen. Means that all UDP ports are already being used throw new RuntimeException(e.getMessage()); } datagramPacket = new DatagramPacket(mBuffer, 1); }
/** * Prepare for the beginning of active use of the public methods of this * component. This method should be called after <code>configure()</code>, * and before any of the public methods of the component are utilized. * * @exception LifecycleException if this component detects a fatal error * that prevents this component from being used */ public void start() throws LifecycleException { // Validate and update our current component state if (started) throw new LifecycleException(sm.getString("standardCluster.alreadyStarted")); try { multicastSocket = new MulticastSocket(multicastPort); if(multicastSocket != null && multicastAddress != null) { multicastSocket.joinGroup(multicastAddress); clusterSender = getClusterSender(getName()); clusterReceiver = getClusterReceiver(getName()); localClusterMember = new ClusterMemberInfo(); localClusterMember.setClusterName(getClusterName()); localClusterMember.setHostName(null); localClusterMember.setClusterInfo(getInfo()); clusterSender.send(localClusterMember); if (debug > 1) log(sm.getString("standardCluster.joinGroup", multicastAddress)); } else { log(sm.getString("standardCluster.socketOrAddressNull")); } } catch (IOException e) { log(sm.getString("standardCluster.joinException", e.toString())); } lifecycle.fireLifecycleEvent(START_EVENT, null); started = true; // Start the background reaper thread threadStart(); }
@Override public void start(CoapReceiver coapReceiver) throws IOException { mcastSocket = new MulticastSocket(bindSocket); mcastSocket.joinGroup(mcastGroup); LOGGER.debug("CoAP server binds on multicast " + mcastSocket.getLocalSocketAddress()); readerThread = new Thread(() -> readingLoop(coapReceiver), "multicast-reader"); readerThread.start(); }