IPv6 组播检查 Java
有没有更好的方法来检查我是否可以接收给定的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
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