package jp.vmi; import java.io.IOException; import java.net.InetAddress; import java.util.Arrays; import java.util.Comparator; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import jp.vmi.Multicast.Receiver; import jp.vmi.Multicast.Sender; public class Main { private static final String MULTICAST_ADDR = "ff35:40:fdb4:353a:c83f:10::10"; // IPv6 // private static final String MULTICAST_ADDR = "224.0.10.0"; // IPv4 private static final int MULTICAST_PORT = 10101; private static final int SEND_WAIT = 300; // msec private static final int DISP_WAIT = 1000; // msec private static final String SENDER_NAME = "IWAMURO Motonori"; private static class Info { public static final int INVALID_NUMBER = -1; public final int num; public final String name; public Info(String msg) { String[] pair = msg.trim().split("\\s+", 2); int num; try { num = Integer.parseInt(pair[0]); } catch (NumberFormatException e) { num = INVALID_NUMBER; } this.num = num; this.name = pair[1].trim(); } @Override public String toString() { if (num == INVALID_NUMBER) return "****** " + name; else return String.format("%06d %s", num, name); } } private final Multicast multicast; private final Map map = new ConcurrentHashMap(); public Main() throws IOException { multicast = new Multicast(MULTICAST_ADDR, MULTICAST_PORT); } void send() throws IOException { Sender sender = multicast.getSender(); int i = 0; while (true) { String msg = String.format("%04d " + SENDER_NAME, ++i); sender.send(msg); try { Thread.sleep(SEND_WAIT); } catch (InterruptedException e) { break; } } } void receive() throws IOException { Receiver receiver = multicast.getReceiver(); while (true) { String msg = receiver.receive(); InetAddress srcAddr = receiver.getAddress(); Info info = new Info(msg); map.put(srcAddr, info); } } void display() { while (true) { Info[] infoArray = map.values().toArray(new Info[0]); Arrays.sort(infoArray, new Comparator() { @Override public int compare(Info info1, Info info2) { return info1.name.compareToIgnoreCase(info2.name); } }); System.out.println("Count: " + infoArray.length); for (Info info : infoArray) { System.out.println(" " + info); } System.out.println(); try { Thread.sleep(DISP_WAIT); } catch (InterruptedException e) { break; } } } public static void main(String[] args) throws IOException { final Main main = new Main(); Thread s = new Thread(new Runnable() { @Override public void run() { try { main.send(); } catch (IOException e) { e.printStackTrace(); } } }); Thread r = new Thread(new Runnable() { @Override public void run() { try { main.receive(); } catch (IOException e) { e.printStackTrace(); } } }); Thread d = new Thread(new Runnable() { @Override public void run() { main.display(); } }); s.start(); r.start(); d.start(); } }