Java Code Examples for java.net.MulticastSocket#joinGroup()

The following examples show how to use java.net.MulticastSocket#joinGroup() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TcpDiscoveryMulticastIpFinder.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 2
Source File: MultiCastManager.java    From openbd-core with GNU General Public License v3.0 6 votes vote down vote up
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() );
  }
}
 
Example 3
Source File: LateralUDPReceiver.java    From commons-jcs with Apache License 2.0 6 votes vote down vote up
/**
 * Constructor for the LateralUDPReceiver object
 *
 * @param multicastAddressString
 * @param multicastPort
 * @throws IOException
 */
protected LateralUDPReceiver( String multicastAddressString, int multicastPort )
    throws IOException
{

    log.debug( "constructing listener, " + multicastAddressString + ":" + multicastPort );

    try
    {
        m_socket = new MulticastSocket( multicastPort );
        m_socket.joinGroup( InetAddress.getByName( multicastAddressString ) );
    }
    catch ( IOException e )
    {
        log.error( e );
        log.debug( "Could not bind to multicast address " + multicastAddressString + ":" + multicastPort );
        //throw e ;//new CacheException( "Could not bind to multicast address " + multicastAddressString + ":" + multicastPort, e);
    }
}
 
Example 4
Source File: Two.java    From JavaBase with MIT License 6 votes vote down vote up
public static void main(String[] args) {
  try {
    InetAddress group = InetAddress.getByName(address);
    MulticastSocket multicastSocket = new MulticastSocket(port);
    multicastSocket.joinGroup(group);
    byte[] buffer = new byte[1024];

    while (true) {
      DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
      multicastSocket.receive(packet);

      String str = new String(packet.getData(), 0, packet.getLength());
      log.info("str={}", str);
    }
  } catch (Exception e) {
    log.error("", e);
  }
}
 
Example 5
Source File: MulticastConnection.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public MulticastConnection(SocketInetAddress address, MessageSerializer<T> serializer) {
    this.address = address;
    this.serializer = serializer;
    try {
        socket = new MulticastSocket(address.getPort());
        socket.joinGroup(address.getAddress());
    } catch (IOException e) {
        throw UncheckedException.throwAsUncheckedException(e);
    }
    localAddress = new SocketInetAddress(socket.getInetAddress(), socket.getLocalPort());
}
 
Example 6
Source File: TP.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
private void bindToInterfaces(java.util.List interfaces, MulticastSocket s) throws IOException {
    SocketAddress group_addr=new InetSocketAddress(diagnostics_addr, diagnostics_port);
    for(Iterator it=interfaces.iterator(); it.hasNext();) {
        NetworkInterface i=(NetworkInterface)it.next();
        try {
            s.joinGroup(group_addr, i);
            if(trace)
                log.trace("joined " + group_addr + " on " + i.getName());
        }
        catch(IOException e) {
            log.warn("failed to join " + group_addr + " on " + i.getName() + ": " + e);
        }
    }
}
 
Example 7
Source File: UDPDiscoveryReceiver.java    From commons-jcs with Apache License 2.0 5 votes vote down vote up
/**
 * Creates the socket for this class.
 * <p>
 * @param multicastInterfaceString
 * @param multicastAddress
 * @param multicastPort
 * @throws IOException
 */
private void createSocket( String multicastInterfaceString, InetAddress multicastAddress,
        int multicastPort )
    throws IOException
{
    try
    {
        mSocket = new MulticastSocket( multicastPort );
        if (log.isInfoEnabled())
        {
            log.info( "Joining Group: [{0}]", multicastAddress );
        }

        // Use dedicated interface if specified
        NetworkInterface multicastInterface = null;
        if (multicastInterfaceString != null)
        {
            multicastInterface = NetworkInterface.getByName(multicastInterfaceString);
        }
        else
        {
            multicastInterface = HostNameUtil.getMulticastNetworkInterface();
        }
        if (multicastInterface != null)
        {
            log.info("Using network interface {0}", multicastInterface.getDisplayName());
            mSocket.setNetworkInterface(multicastInterface);
        }

        mSocket.joinGroup( multicastAddress );
    }
    catch ( IOException e )
    {
        log.error( "Could not bind to multicast address [{0}:{1}]", multicastAddress,
                multicastPort, e );
        throw e;
    }
}
 
Example 8
Source File: NetUtils.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param multicastSocket
 * @param multicastAddress
 */
public static void joinMulticastGroup(MulticastSocket multicastSocket, InetAddress multicastAddress)
    throws IOException {
    setInterface(multicastSocket, multicastAddress instanceof Inet6Address);
    multicastSocket.setLoopbackMode(false);
    multicastSocket.joinGroup(multicastAddress);
}
 
Example 9
Source File: SsdpDiscovery.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 10
Source File: UdpMulticastDataSource.java    From Exoplayer_VLC with Apache License 2.0 5 votes vote down vote up
@Override
public long open(DataSpec dataSpec) throws IOException {
    socket = new MulticastSocket(dataSpec.uri.getPort());
    InetSocketAddress socketAddress = new InetSocketAddress(dataSpec.uri.getHost(), dataSpec.uri.getPort());
    groupAddr = socketAddress.getAddress();
    socket.joinGroup(groupAddr);
    opened = true;
    return 0;
}
 
Example 11
Source File: MulticastServerImpl.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Starts up the server. The server that has started accepts and handles multicast datagram packets.
 *
 * @throws IllegalStateException if the server has already started.
 * @throws IOException           if IOException occurred at startup
 * @noinspection OverlyBroadCatchBlock, ThrowCaughtLocally, SocketOpenedButNotSafelyClosed
 */
public void startup() throws IOException {

   assureNotStarted();

   // Issue an information notification.
   informServerStarting();

   try {

      // Initialize socket
      multicastSocket = new MulticastSocket(multicastPort);
      multicastSocket.setReceiveBufferSize(RECEIVE_BUFFER_SIZE);
      multicastSocket.joinGroup(multicastAddress);

      // Notify that started
      informServerStarted();

      // Start listener thread
      final Thread listenerThread = new DaemonThreadFactory(threadFactoryName).newThread(this);
      listenerThread.start();

      started = true;
   } catch (final IOException e) {

      IOUtils.closeHard(multicastSocket);

      throw e;
   }
}
 
Example 12
Source File: UDPMulticastReceiver.java    From moleculer-java with MIT License 5 votes vote down vote up
@Override
protected void connect() throws Exception {

	// Start multicast receiver
	multicastReceiver = new MulticastSocket(udpPort);
	multicastReceiver.setReuseAddress(udpReuseAddr);

	InetAddress inetAddress = InetAddress.getByName(udpAddress);
	if (netIf == null) {
		multicastReceiver.joinGroup(inetAddress);
	} else {
		InetSocketAddress socketAddress = new InetSocketAddress(inetAddress, udpPort);
		try {
			multicastReceiver.joinGroup(socketAddress, netIf);
		} catch (Exception unsupportedAddress) {
			disconnect();
			return;
		}
	}

	// Start thread
	super.connect();

	// Log
	String msg = "Multicast discovery service started on udp://" + udpAddress + ':' + udpPort;
	if (netIf == null) {
		logger.info(msg + '.');
	} else {
		logger.info(msg + " (" + netIf.getDisplayName() + ").");
	}
}
 
Example 13
Source File: ClientConnection.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
public MulticastSocket connectWithTimeout(int msTimeOut) throws IOException {
    MulticastSocket socket = new MulticastSocket(port);
    socket.joinGroup(address);
    socket.setSoTimeout(msTimeOut);
    return socket;
}
 
Example 14
Source File: WirelessHidService.java    From WirelessHid with Apache License 2.0 4 votes vote down vote up
public void startDiscover() {

            try {
                mMulticastSocket = new MulticastSocket(Constant.HID_MULTICAST_PORT);
                group = InetAddress.getByName(Constant.HID_MULTICAST_ADDRESS);
                mMulticastSocket.joinGroup(group);
            } catch (IOException e) {
                e.printStackTrace();
                return;
            }

            listenerThread = new Thread(new Runnable() {
                // listen response from pc.
                @Override
                public void run() {
                    try {
                        DatagramPacket packet;
                        packet = new DatagramPacket(new byte[256], 256);

                        while (true) {
                            mMulticastSocket.receive(packet);

                            String rsp = new String(packet.getData()).trim();
                            Log.d(TAG, "rsp: " + rsp);
                            if (Constant.HID_SERVICE_DISCOVERY_RSP.equals(rsp)) {
                                Log.d(TAG, "get response from pc.");
                                break;
                            } else {
                                Log.d(TAG, "It is not a valid response, just ignore it.");
                                packet.setData(new byte[256]);
                            }
                        }

                        // send message to activity to stop progress dialog.
                        if (mUIHandler != null) {
                            mUIHandler.obtainMessage(MainActivity.MSG_FOUND_SERVICE).sendToTarget();
                        }

                        mPCIPAddress = packet.getAddress();
                        Log.d(TAG, "pc ip address: " + packet.getSocketAddress().toString());

                        // interrupt scanner thread to stop scan cause we have found pc.
                        scannerThread.interrupt();

                        // start data send thread.
                        new DataSendThread().start();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
            scannerThread = new Thread(new Runnable() {
                // pc finder thread.
                @Override
                public void run() {
                    try {
                        DatagramPacket packet = new DatagramPacket(Constant.HID_SERVICE_DISCOVERY_REQ.getBytes(),
                                Constant.HID_SERVICE_DISCOVERY_REQ.length(),
                                group, Constant.HID_MULTICAST_PORT);
                        while (true) {
                            if (scannerThread.isInterrupted()) {
                                break;
                            }

                            Log.d(TAG, "discovery pc......");
                            mMulticastSocket.send(packet);

                            // try again after 2s.
                            try {
                                Thread.sleep(2000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                                break;
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });

            // start discover thread.
            scannerThread.start();
            listenerThread.start();
        }
 
Example 15
Source File: ClientConnection.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
public MulticastSocket connectWithTimeout(int msTimeOut) throws IOException {
    MulticastSocket socket = new MulticastSocket(port);
    socket.joinGroup(address);
    socket.setSoTimeout(msTimeOut);
    return socket;
}
 
Example 16
Source File: ServerUtil.java    From servicecomb-java-chassis with Apache License 2.0 4 votes vote down vote up
private static void initMulticastSocket() throws IOException {
  multicastSocket = new MulticastSocket(PORT);
  group = InetAddress.getByName(GROUP);
  multicastSocket.joinGroup(group); // need to join the group to be able to receive the data
}
 
Example 17
Source File: ClientConnection.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
public MulticastSocket connectWithTimeout(int msTimeOut) throws IOException {
    MulticastSocket socket = new MulticastSocket(port);
    socket.joinGroup(address);
    socket.setSoTimeout(msTimeOut);
    return socket;
}
 
Example 18
Source File: ClientConnection.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
public MulticastSocket connectWithTimeout(int msTimeOut) throws IOException {
    MulticastSocket socket = new MulticastSocket(port);
    socket.joinGroup(address);
    socket.setSoTimeout(msTimeOut);
    return socket;
}
 
Example 19
Source File: MulticastServer.java    From Azzet with Open Software License 3.0 4 votes vote down vote up
@Override
protected void onBind() throws IOException
{
	serverSocket = new MulticastSocket( serverPort );
	serverSocket.joinGroup( serverGroup );
}
 
Example 20
Source File: ClientConnection.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
public MulticastSocket connectWithTimeout(int msTimeOut) throws IOException {
    MulticastSocket socket = new MulticastSocket(port);
    socket.joinGroup(address);
    socket.setSoTimeout(msTimeOut);
    return socket;
}