how-to

Network

How to make easy socket client (DayTime protocol)

For this example you need to use:

import java.io.*;
import java.net.*;

This network client uses very easy DayTime protocol to read current time. The DayTime server is running on port 13.

try {
  /* -- create connection to server on port 13 */

  Socket s = new Socket( "time-b.timefreq.bldrdoc.gov", 13 );

  /* -- stream for reading data */

  DataInputStream from = new DataInputStream( s.getInputStream() );

  /* -- try to read data */

  StringBuilder time = new StringBuilder();
  int i;
  while ( ( i = from.read() ) != -1 ) time.append( (char) i );

  /* -- show data */

  System.out.println( time.toString() );

} catch (UnknownHostException ex) {
  Logger.getLogger(Window.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
  Logger.getLogger(Window.class.getName()).log(Level.SEVERE, null, ex);
}
When the DayTime server is running, the output could be:
56215 12-10-15 11:14:06 21 0 0  65.9 UTC(NIST) *