Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/sample/nio/multicast/Reader.java
38829 views
/*1* Copyright (c) 2007, 2011, Oracle and/or its affiliates. All rights reserved.2*3* Redistribution and use in source and binary forms, with or without4* modification, are permitted provided that the following conditions5* are met:6*7* - Redistributions of source code must retain the above copyright8* notice, this list of conditions and the following disclaimer.9*10* - Redistributions in binary form must reproduce the above copyright11* notice, this list of conditions and the following disclaimer in the12* documentation and/or other materials provided with the distribution.13*14* - Neither the name of Oracle nor the names of its15* contributors may be used to endorse or promote products derived16* from this software without specific prior written permission.17*18* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS19* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,20* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR21* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR22* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,23* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,24* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR25* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF26* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING27* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS28* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.29*/3031/*32* This source code is provided to illustrate the usage of a given feature33* or technique and has been deliberately simplified. Additional steps34* required for a production-quality application, such as security checks,35* input validation and proper error handling, might not be present in36* this sample code.37*/383940import java.nio.channels.*;41import java.nio.charset.*;42import java.nio.ByteBuffer;43import java.net.*;44import java.io.IOException;45import java.util.*;4647public class Reader {4849static void usage() {50System.err.println("usage: java Reader group:port@interf [-only source...] [-block source...]");51System.exit(-1);52}5354static void printDatagram(SocketAddress sa, ByteBuffer buf) {55System.out.format("-- datagram from %s --\n",56((InetSocketAddress)sa).getAddress().getHostAddress());57System.out.println(Charset.defaultCharset().decode(buf));58}5960static void parseAddessList(String s, List<InetAddress> list)61throws UnknownHostException62{63String[] sources = s.split(",");64for (int i=0; i<sources.length; i++) {65list.add(InetAddress.getByName(sources[i]));66}67}6869public static void main(String[] args) throws IOException {70if (args.length == 0)71usage();7273// first parameter is the multicast address (interface required)74MulticastAddress target = MulticastAddress.parse(args[0]);75if (target.interf() == null)76usage();7778// addition arguments are source addresses to include or exclude79List<InetAddress> includeList = new ArrayList<InetAddress>();80List<InetAddress> excludeList = new ArrayList<InetAddress>();81int argc = 1;82while (argc < args.length) {83String option = args[argc++];84if (argc >= args.length)85usage();86String value = args[argc++];87if (option.equals("-only")) {88parseAddessList(value, includeList);89continue;90}91if (option.equals("-block")) {92parseAddessList(value, excludeList);93continue;94}95usage();96}97if (!includeList.isEmpty() && !excludeList.isEmpty()) {98usage();99}100101// create and bind socket102ProtocolFamily family = StandardProtocolFamily.INET;103if (target.group() instanceof Inet6Address) {104family = StandardProtocolFamily.INET6;105}106DatagramChannel dc = DatagramChannel.open(family)107.setOption(StandardSocketOptions.SO_REUSEADDR, true)108.bind(new InetSocketAddress(target.port()));109110if (includeList.isEmpty()) {111// join group and block addresses on the exclude list112MembershipKey key = dc.join(target.group(), target.interf());113for (InetAddress source: excludeList) {114key.block(source);115}116} else {117// join with source-specific membership for each source118for (InetAddress source: includeList) {119dc.join(target.group(), target.interf(), source);120}121}122123// register socket with Selector124Selector sel = Selector.open();125dc.configureBlocking(false);126dc.register(sel, SelectionKey.OP_READ);127128// print out each datagram that we receive129ByteBuffer buf = ByteBuffer.allocateDirect(4096);130for (;;) {131int updated = sel.select();132if (updated > 0) {133Iterator<SelectionKey> iter = sel.selectedKeys().iterator();134while (iter.hasNext()) {135SelectionKey sk = iter.next();136iter.remove();137138DatagramChannel ch = (DatagramChannel)sk.channel();139SocketAddress sa = ch.receive(buf);140if (sa != null) {141buf.flip();142printDatagram(sa, buf);143buf.rewind();144buf.limit(buf.capacity());145}146}147}148}149}150}151152153