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

The following examples show how to use java.net.MulticastSocket#send() . 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: JmDNSImpl.java    From DeviceConnect-Android with MIT License 6 votes vote down vote up
/**
 * 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);
        }
    }
}
 
Example 2
Source File: PlainMulticastSender.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
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;
            }
         }
      }
   }
 
Example 3
Source File: SAdvertise.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    if (args.length != 3) {
        System.out.println("Usage: SAdvertize localaddress multicastaddress port");
        System.out.println("java SAdvertize 10.16.88.178 224.0.1.105 23364");
        System.out.println("send from 10.16.88.178:23364 to 224.0.1.105:23364");
        System.exit(1);
    }
    InetAddress group = InetAddress.getByName(args[1]);
    InetAddress addr = InetAddress.getByName(args[0]);
    int port = Integer.parseInt(args[2]);
    InetSocketAddress addrs = new InetSocketAddress(addr, port);

    MulticastSocket s = new MulticastSocket(addrs);
    s.setTimeToLive(29);
    s.joinGroup(group);
    boolean ok = true;
    while (ok) {
        byte[] buf = new byte[1000];
        DatagramPacket recv = new DatagramPacket(buf, buf.length, group, port);
        System.out.println("sending from: " + addr);
        s.send(recv);
        Thread.currentThread().sleep(2000);
    }
    s.leaveGroup(group);
}
 
Example 4
Source File: UDP.java    From openvisualtraceroute with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static void test() throws Exception {
	final String hostname = "google.com";
	final String localhost = "localhost";
	final MulticastSocket datagramSocket = new MulticastSocket();
	datagramSocket.setSoTimeout(10000);
	short ttl = 1;
	final InetAddress receiverAddress = InetAddress.getByName(hostname);
	while (ttl < 100) {
		try {
			byte[] buffer = "0123456789".getBytes();
			datagramSocket.setTimeToLive(ttl++);
			final DatagramPacket sendPacket = new DatagramPacket(buffer, buffer.length, receiverAddress, 80);

			datagramSocket.send(sendPacket);

			buffer = new byte[10];
			final DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length);

			datagramSocket.receive(receivePacket);
			System.out.println("ttl=" + ttl + " address=" + receivePacket.getAddress().getHostAddress() + " data="
					+ new String(receivePacket.getData()));
			Thread.sleep(1000);
		} catch (final SocketTimeoutException e) {
			System.out.println("timeout ttl=" + ttl);
		}
	}
}
 
Example 5
Source File: One.java    From JavaBase with MIT License 5 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);
    while (true) {
      byte[] buffer = "One".getBytes();
      DatagramPacket packet = new DatagramPacket(buffer, buffer.length, group, port);
      multicastSocket.send(packet);
      Thread.sleep(1000);
    }
  } catch (Exception e) {
    log.error("", e);
  }
}
 
Example 6
Source File: Multicast.java    From Bitcoin with Apache License 2.0 5 votes vote down vote up
public static void sendData(MulticastSocket s, int ourTTL, byte[] buffer) throws IOException {
    // Create a DatagramPacket 
    final DatagramPacket pack = new DatagramPacket(buffer, buffer.length, InetAddress.getByName(GROUP), PORT);
    // Get the current TTL, set our TTL, do a send, reset the TTL  
    final int ttl = s.getTimeToLive(); 
    s.setTimeToLive(ourTTL); 
    s.send(pack); 
    s.setTimeToLive(ttl);
}
 
Example 7
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 8
Source File: SsdpDiscovery.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
private static void sendNotify(String notifyMessage, InetAddress ia) throws Exception {
    MulticastSocket socket = new MulticastSocket(null);
    try {
        socket.bind(new InetSocketAddress(PORT));
        socket.setTimeToLive(4);
        byte[] data = notifyMessage.toString().getBytes();
        socket.send(new DatagramPacket(data, data.length, new InetSocketAddress(ia, PORT)));
    } catch (Exception e) {
        logger.error("sendNotify", e);
        throw e;
    } finally {
        socket.disconnect();
        socket.close();
    }
}
 
Example 9
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 10
Source File: Question.java    From hola with MIT License 4 votes vote down vote up
private void askWithGroup(InetAddress group, MulticastSocket socket) throws IOException {
    DatagramPacket packet = new DatagramPacket(buffer.array(), buffer.position(), group, Query.MDNS_PORT);
    packet.setAddress(group);
    socket.send(packet);
}