我正在学习DatagramChannel Multicast,
我正在尝试执行以下操作,我注意到当我在VPN上并且没有收到任何内容时,DatagramChannel#receive方法完全阻塞,但是当我断开VPN时,数据会被打印几次。
1。将数据发送到多播IP组:
import java.io.IOException;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.util.Date;
public class MultiCastChannelThread extends Thread {
DatagramChannel channel;
ProtocolFamily family = StandardProtocolFamily.INET;
MultiCastChannelThread(String name) throws IOException {
super(name);
configureChannel();
}
public static void main(String[] args) throws IOException {
new MultiCastChannelThread("MultiCastChannel").start();
}
private void configureChannel() throws IOException {
channel = DatagramChannel.open(family).setOption(StandardSocketOptions.SO_REUSEADDR, true).bind(null).setOption(
StandardSocketOptions.IP_MULTICAST_IF, NetworkInterface.getByName("wlan0"));
}
@Override
public void run() {
int i = 0;
while (i++ < 6) {
try {
byte[] buff = new Date().toString().getBytes();
ByteBuffer buffer = ByteBuffer.wrap(buff);
InetAddress group = InetAddress.getByName("224.0.15.15");
int sent = channel.send(buffer, new InetSocketAddress(group, 4466));
System.out.format("Number of bytes sent :%s\n Data sent:%s\t\n", sent, new String(buff));
try {
sleep(5 * 1000);
} catch (InterruptedException e) {
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2。加入和接收群组数据
import static java.lang.Thread.sleep;
import java.io.IOException;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
public class MulticastChannelClient {
NetworkInterface networkInterface;
InetAddress inetAddress;
InetAddress group;
ProtocolFamily family = StandardProtocolFamily.INET;
public MulticastChannelClient() throws UnknownHostException, SocketException {
group = InetAddress.getByName("224.0.15.15");
networkInterface = NetworkInterface.getByName("wlan0");
}
public static void main(String[] args) throws IOException {
new MulticastChannelClient().testMultiCastChannel();
}
private void testMultiCastChannel() throws IOException {
new MultiCastChannelThread("MulticastChannelTest").start();
DatagramChannel channel = DatagramChannel.open(family).setOption(StandardSocketOptions.SO_REUSEADDR, true).bind(
new InetSocketAddress((InetAddress) null, 4466));
channel.join(group, networkInterface);
for (int i = 0; i < 6; i++) {
ByteBuffer received = ByteBuffer.allocate(250);
SocketAddress socketAddress = channel.receive(received);
System.out.println("Received ::: " + i + " " + new String(received.array()));
try {
sleep(2 * 1000);
} catch (InterruptedException e) {
}
}
}
}