IPv6 组播检查 Java

发布于 2024-10-02 10:57:42 字数 980 浏览 0 评论 0原文

有没有更好的方法来检查我是否可以接收给定的 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) {
        }
    }
}

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦在深巷 2024-10-09 10:57:42

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

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

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文