Using Datagrams to Get the Date : UDP « Network Protocol « Java






Using Datagrams to Get the Date

   
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class GetDate {
  final static int PortDayTime = 13; // well-known daytime port

  public static void main(String args[]) throws Exception {
    byte msg[] = new byte[256];
    DatagramSocket dgSocket = new DatagramSocket();
    InetAddress destination = InetAddress.getByName("web.mit.edu");
    DatagramPacket datagram = new DatagramPacket(msg, msg.length,
        destination, PortDayTime);
    dgSocket.send(datagram);
    datagram = new DatagramPacket(msg, msg.length);
    dgSocket.receive(datagram);
    String received = new String(datagram.getData());
    System.out.println("The time in Cambridge is now: " + received);
    dgSocket.close();
  }
}
           
         
    
    
  








Related examples in the same category

1.Udp Echo Server
2.DatagramSocket Server
3.DatagramSocket Client
4.Send out UDP pockets
5.Receive UDP pocketsReceive UDP pockets
6.Experiment with UDP sockets
7.An echo server using UDP socketsAn echo server using UDP sockets
8.Connect to a daytime server using the UDP protocol
9.Handles TCP and UDP connections and provides exception handling and error logging
10.UDP OutputStream
11.UDP InputStream
12.Performs broadcast and multicast peer detection.