简体   繁体   中英

IPv6 Multicast Check Java

Is there any better to way to check if I can receive a given IP Multicast transmission. Following code works fine but there is a problem in this code - it blocks the current thread until it gets the multicast packets.

Thank you.

import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

public class MulticastTest {

    static String MCAST_ADDR = "FF7E:230::1234";// "235.1.1.1";
    static int DEST_PORT = 1234;
    static int BUFFER_LENGTH = 16;

    public static void main(String args[]) {

        try {
            byte[] b = new byte[BUFFER_LENGTH];
            DatagramPacket dgram = new DatagramPacket(b, b.length);
            MulticastSocket socket = new MulticastSocket(DEST_PORT); 
            socket.joinGroup(InetAddress.getByName(MCAST_ADDR));
            socket.receive(dgram); // blocks until a datagram is received
            System.err.println("Received " + dgram.getLength() + " bytes from " + dgram.getAddress());
            dgram.setLength(b.length); // must reset length field!
        } catch (Exception e) {
        }
    }
}

You could set a timeout-value with the method socket.setSoTimeout(int) .

http://download.oracle.com/javase/1.4.2/docs/api/java/net/Socket.html#setSoTimeout(int )

If you don't receive any data within the timeout, a SocketTimeoutException is raised

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM