01: 02: //************ Datagram Timeserver uses list of client in a file ******** 03: 04: import java.net.DatagramSocket; 05: import java.net.DatagramPacket; 06: import java.net.InetSocketAddress; 07: import java.util.Date; 08: import java.util.List; 09: import java.util.ArrayList; 10: import java.util.Iterator; 11: import java.io.BufferedReader; 12: import java.io.FileReader; 13: import java.io.IOException; 14: public class TimeServerDG { 15: public static void main(String[ ] args) { 16: if (args.length < 1) { 17: System.err.println("Usage: TimeServerDG <file>"); 18: return; 19: } 20: try { 21: // Read recipient list from file. 22: List recipients = new ArrayList(); 23: BufferedReader in = 24: new BufferedReader(new FileReader(args[0])); 25: String next = null; 26: while ((next = in.readLine()) != null) 27: recipients.add(next); 28: in.close(); 29: // Addresses, DatagramSocket, and DatagramPacket 30: InetSocketAddress[ ] hosts = 31: new InetSocketAddress[recipients.size()]; 32: Iterator it = recipients.iterator(); 33: int i = 0; 34: // Convert string addresses to InetSocketAddresses 35: while (it.hasNext()) 36: hosts[i++] = 37: new InetSocketAddress((String) it.next(), port); 38: DatagramSocket time_socket = new DatagramSocket(); 39: 40: // Packet to hold data 41: byte[ ] t_bytes = new Date().toString().getBytes(); 42: DatagramPacket time_packet = 43: new DatagramPacket(t_bytes, t_bytes.length); 44: 45: // Send a packet to each recipient every N seconds. 46: while (true) { 47: t_bytes = new Date().toString().getBytes(); 48: time_packet.setData(t_bytes); 49: for (i = 0; i < hosts.length; i++) { 50: time_packet.setSocketAddress(hosts[i]); 51: time_socket.send(time_packet); 52: } 53: Thread.sleep(winks); // pause 54: } 55: } 56: catch(IOException e) { System.err.println(e); } 57: catch(InterruptedException e) { System.err.println(e); } 58: } 59: private static final int port = 10001; 60: private static final int winks = 10000; // milliseconds 61: }