Advertisement
Guest User

Untitled

a guest
May 5th, 2015
240
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.32 KB | None | 0 0
  1. import java.io.*;
  2. import java.net.*;
  3.  
  4. public class TimeServer {
  5.  
  6.     // server port
  7.     static private final int port = 6789;
  8.    
  9.     public static void main(String[] args) {
  10.        
  11.         // multicast address
  12.         String dategroup;
  13.        
  14.         // get the multicast address in input
  15.         dategroup = args[0];
  16.        
  17.         DatagramSocket ms = null;
  18.        
  19.         System.out.println("S> Server ready");
  20.        
  21.         try {
  22.             // create inet address
  23.             InetAddress ia = InetAddress.getByName(dategroup);
  24.            
  25.             byte [] data;
  26.             long time;
  27.            
  28.             // create the datagram socket
  29.             ms = new DatagramSocket(2000);
  30.            
  31.             // infinite cycle
  32.             while(true) {
  33.                 // get the time
  34.                 time = System.currentTimeMillis();
  35.                
  36.                 // convert the time in a String, then in byte array
  37.                 data = Long.toString(time).getBytes();
  38.                
  39.                 // create the datagram packet to send
  40.                 DatagramPacket dp = new DatagramPacket(data, data.length, ia, port);
  41.                
  42.                 // send the packet
  43.                 ms.send(dp);
  44.                
  45.                 // sleep a bit
  46.                 try {
  47.                     Thread.sleep(3000);
  48.                 }
  49.                 catch(InterruptedException e) {
  50.                     System.out.println("S> INTERROTTO: " + e.toString());
  51.                 }
  52.                
  53.             }      
  54.         }
  55.         catch(IOException e) {
  56.             System.out.println("S> ERROR: "+e.toString());
  57.         }
  58.         finally {
  59.             // close datagram socket in case of exception
  60.             if(ms != null)
  61.                 ms.close();
  62.         }
  63.        
  64.     }
  65.  
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement