IPv6组播检查Java

时间:2010-11-12 10:54:24

标签: java network-programming

有没有更好的方法来检查我是否可以接收给定的IP多播传输。以下代码工作正常,但此代码中存在问题 - 它阻止当前线程,直到它获取多播数据包。

谢谢。

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) {
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您可以使用方法socket.setSoTimeout(int)设置超时值。

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

如果在超时内没有收到任何数据,则会引发SocketTimeoutException