下面列出了java.nio.channels.DatagramChannel#join() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/** Try to listen to multicast messages
* @param udp UDP channel that should listen to multicast messages
* @param port Port to use
* @return Local multicast address, or <code>null</code> if no multicast support
*/
public static InetSocketAddress configureMulticast(final DatagramChannel udp, final int port)
{
try
{
final NetworkInterface loopback = getLoopback();
if (loopback != null)
{
final InetAddress group = InetAddress.getByName(PVASettings.EPICS_PVA_MULTICAST_GROUP);
final InetSocketAddress local_broadcast = new InetSocketAddress(group, port);
udp.join(group, loopback);
logger.log(Level.CONFIG, "Multicast group " + local_broadcast + " using network interface " + loopback.getDisplayName());
udp.setOption(StandardSocketOptions.IP_MULTICAST_LOOP, true);
udp.setOption(StandardSocketOptions.IP_MULTICAST_IF, loopback);
return local_broadcast;
}
}
catch (Exception ex)
{
logger.log(Level.WARNING, "Cannot configure multicast support", ex);
}
return null;
}
@Test
public void TestServer() throws Exception {
//接受组播和发送组播的数据报服务都要把组播地址添加进来
String host = "239.239.239.88";//多播地址
int port = 9998;
InetAddress group = InetAddress.getByName(host);
DatagramChannel channel = DatagramChannel.open(StandardProtocolFamily.INET);
channel.bind(new InetSocketAddress(port));
channel.join(group, Utils.getLocalNetworkInterface());
ByteBuffer buffer = ByteBuffer.allocate(1024);
SocketAddress sender = channel.receive(buffer);
buffer.flip();
byte[] data = new byte[buffer.remaining()];
buffer.get(data);
System.out.println(new String(data));
}
@Test
public void testSend() throws Exception {
String host = "239.239.239.99";//多播地址
int port = 9999;
InetAddress group = InetAddress.getByName(host);
String message = "test-multicastSocket";
DatagramChannel channel = DatagramChannel.open(StandardProtocolFamily.INET);
channel.configureBlocking(true);
channel.bind(new InetSocketAddress(port));
channel.join(group, Utils.getLocalNetworkInterface());
InetSocketAddress sender = new InetSocketAddress("239.239.239.99", 4000);
channel.send(ByteBuffer.wrap(message.getBytes()), sender);
channel.close();
}
public static MarketData open(NetworkInterface multicastInterface,
InetSocketAddress multicastGroup, InetSocketAddress requestAddress,
long instrument) throws IOException {
DatagramChannel channel = DatagramChannel.open(StandardProtocolFamily.INET);
channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
channel.bind(new InetSocketAddress(multicastGroup.getPort()));
channel.join(multicastGroup.getAddress(), multicastInterface);
channel.configureBlocking(false);
DatagramChannel requestChannel = DatagramChannel.open(StandardProtocolFamily.INET);
requestChannel.configureBlocking(false);
return new MarketData(channel, requestChannel, requestAddress, instrument);
}
private synchronized DatagramChannel getChannel() throws IOException {
if (channel == null || !channel.isOpen()) {
if (shutdown.get()) {
throw new IllegalStateException("Channel has been shut down");
}
ProtocolFamily protocolFamily = InternetProtocolUtils.getProtocolFamily(group.getAddress().getAddress());
DatagramChannel _channel = selector.provider().openDatagramChannel(protocolFamily);
_channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
// bind to any-local before setting TTL
int port = group.getAddress().getPort();
if (protocolFamily == StandardProtocolFamily.INET) {
_channel.bind(new InetSocketAddress(Inet4Address.getByName("0.0.0.0"), port));
} else {
_channel.bind(new InetSocketAddress(Inet6Address.getByName("[::]"), port));
}
int timeToLive = group.getTimeToLive();
if (timeToLive != 1) {
_channel.setOption(StandardSocketOptions.IP_MULTICAST_TTL, timeToLive);
}
for (NetworkInterface iface : networkInterfaces) {
_channel.join(group.getAddress().getAddress(), iface);
}
_channel.configureBlocking(false);
channel = _channel;
}
return channel;
}
/**
* Receive messages. Invoke the message listener on each message. Continue
* until a packet indicating the End of Session is received.
*
* @param multicastInterface the multicast interface
* @param multicastGroup the multicast group
* @param requestAddress the request address
* @param listener a message listener
* @throws IOException if an I/O error occurs
*/
public static void receive(NetworkInterface multicastInterface,
InetSocketAddress multicastGroup, InetSocketAddress requestAddress,
MessageListener listener) throws IOException {
DatagramChannel channel = DatagramChannel.open(StandardProtocolFamily.INET);
channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
channel.bind(new InetSocketAddress(multicastGroup.getPort()));
channel.join(multicastGroup.getAddress(), multicastInterface);
channel.configureBlocking(false);
DatagramChannel requestChannel = DatagramChannel.open(StandardProtocolFamily.INET);
requestChannel.configureBlocking(false);
StatusListener statusListener = new StatusListener();
try (Selector selector = Selector.open();
MoldUDP64Client client = new MoldUDP64Client(channel, requestChannel,
requestAddress, listener, statusListener)) {
SelectionKey channelKey = channel.register(selector, SelectionKey.OP_READ);
SelectionKey requestChannelKey = requestChannel.register(selector, SelectionKey.OP_READ);
while (statusListener.receive) {
while (selector.select() == 0);
Set<SelectionKey> selectedKeys = selector.selectedKeys();
if (selectedKeys.contains(channelKey))
client.receive();
if (selectedKeys.contains(requestChannelKey))
client.receiveResponse();
selectedKeys.clear();
}
}
}
static DatagramChannel openClientChannel() throws IOException {
DatagramChannel channel = DatagramChannel.open(StandardProtocolFamily.INET);
channel.bind(null);
channel.setOption(StandardSocketOptions.IP_MULTICAST_IF, loopbackInterface());
channel.join(multicastGroup(), loopbackInterface());
return channel;
}