Time server using java

About Me

Hi I’m Madushanka Perera from Srilanka.
I’m studying in the Computer Science and Engineering field
I’m Create this blog for share my IT knowledge with you…….
So I’m publishing here special things I learned while playing around with my laptop…………
Dont forget to make Comment.

How to hire me ?

If you want create android application , have you stuck with your final year project , if you want to create android app with your own ideas.

just contact me i’l be there for you. D

Phone — +94 757461232
Email — madushanka.perera@ymail.com
Skype — maduzz23
Twitter — maduzz23

Madushanka’s IT Blog

Categories

Blog Stats

Blog Views

Simple UDP Time Server using Java

Today i am going to tell you how to develop simple time sever using java.net class with UDP.

This is a simple UDP server and client programs. The server runs on a local computer, waiting for a datagram request from a remote computer asking for the server’s current time. The server then returns its current time to the client, which in turn displays it.

Screenshot at 2013-01-21 15:31:20

Server Program >>>>> Server.java

import java.net.*; import java.io.*; import java.util.*; public class Server < public static void main(String[] args) throws Exception< DatagramSocket ss=new DatagramSocket(1234); while(true)< System.out.println("Server is up. "); byte[] rd=new byte[100]; byte[] sd=new byte[100]; DatagramPacket rp=new DatagramPacket(rd,rd.length); ss.receive(rp); InetAddress ip= rp.getAddress(); int port=rp.getPort(); Date d=new Date(); // getting system time String time= d + ""; // converting it to String sd=time.getBytes(); // converting that String to byte DatagramPacket sp=new DatagramPacket(sd,sd.length,ip,port); ss.send(sp); rp=null; System.out.println("Done !! "); >> >

Client program >>>>>>>>> Clientnew.java

import java.net.*; import java.io.*; public class Clientnew < public static void main(String[] args) throws Exception< System.out.println("Server Time >>>>"); DatagramSocket cs=new DatagramSocket(); InetAddress ip=InetAddress.getByName("localhost"); byte[] rd=new byte[100]; byte[] sd=new byte[100]; DatagramPacket sp=new DatagramPacket(sd,sd.length,ip,1234); DatagramPacket rp=new DatagramPacket(rd,rd.length); cs.send(sp); cs.receive(rp); String time=new String(rp.getData()); System.out.println(time); cs.close(); > >

Источник

Time server using java

Non-Blocking Time Server NIO Example

This example implements a non-blocking internet time server.

public class NBTimeServer < private static final int DEFAULT_TIME_PORT = 8900; // Constructor with no arguments creates a time server on default port. public NBTimeServer() throws Exception < acceptConnections(this.DEFAULT_TIME_PORT); >// Constructor with port argument creates a time server on specified port. public NBTimeServer(int port) throws Exception < acceptConnections(port); >// Accept connections for current time. Lazy Exception thrown. private static void acceptConnections(int port) throws Exception < // Selector for incoming time requests Selector acceptSelector = SelectorProvider.provider().openSelector(); // Create a new server socket and set to non blocking mode ServerSocketChannel ssc = ServerSocketChannel.open(); ssc.configureBlocking(false); // Bind the server socket to the local host and port InetAddress lh = InetAddress.getLocalHost(); InetSocketAddress isa = new InetSocketAddress(lh, port); ssc.socket().bind(isa); // Register accepts on the server socket with the selector. This // step tells the selector that the socket wants to be put on the // ready list when accept operations occur, so allowing multiplexed // non-blocking I/O to take place. SelectionKey acceptKey = ssc.register(acceptSelector, SelectionKey.OP_ACCEPT); int keysAdded = 0; // Here's where everything happens. The select method will // return when any operations registered above have occurred, the // thread has been interrupted, etc. while ((keysAdded = acceptSelector.select()) >0) < // Someone is ready for I/O, get the ready keys SetreadyKeys = acceptSelector.selectedKeys(); Iterator i = readyKeys.iterator(); // Walk through the ready keys collection and process date requests. while (i.hasNext()) < SelectionKey sk = (SelectionKey) i.next(); i.remove(); // The key indexes into the selector so you // can retrieve the socket that's ready for I/O ServerSocketChannel nextReady = (ServerSocketChannel) sk .channel(); // Accept the date request and send back the date string Socket s = nextReady.accept().socket(); // Write the current time to the socket PrintWriter out = new PrintWriter(s.getOutputStream(), true); Date now = new Date(); out.println(now); out.close(); >> > // Entry point. public static void main(String[] args) < // Parse command line arguments and // create a new time server (no arguments yet) try < NBTimeServer nbt = new NBTimeServer(); >catch (Exception e) < e.printStackTrace(); >> >

Источник

How to use an internet time server to get the time in Java?

Java provides several classes and methods to synchronize the time of the system with an Internet Time Server. This can be useful when the time on a system may be incorrect or out of sync with the actual time, and a more accurate time is needed for various purposes such as time-sensitive applications, security, or cryptography.

Method 1: Using the java.net.InetAddress class

To get the time from an Internet time server using the java.net.InetAddress class in Java, you can follow these steps:

  1. Create an instance of the InetAddress class with the IP address of the time server you want to use. In this example, we’ll use the time server at time.nist.gov .
InetAddress address = InetAddress.getByName("time.nist.gov");
  1. Open a socket connection to the time server on port 13, which is the standard port for the time service.
Socket socket = new Socket(address, 13);
  1. Read the response from the time server. The response will be a string in the format «JJJJJJJJJJj» where J is the Julian date and j is the number of milliseconds since midnight.
InputStream in = socket.getInputStream(); Scanner scanner = new Scanner(in); String response = scanner.nextLine();
  1. Parse the response to get the time. The Julian date can be converted to a Date object using the java.util.Calendar class. The number of milliseconds can be converted to a Date object using the java.util.Date class.
int julianDate = Integer.parseInt(response.substring(1, 4)); int milliseconds = Integer.parseInt(response.substring(5, 10)); Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.YEAR, 2000); calendar.set(Calendar.DAY_OF_YEAR, julianDate); Date date = calendar.getTime(); date.setTime(date.getTime() + milliseconds);
import java.io.*; import java.net.*; import java.util.*; public class TimeClient  public static void main(String[] args) throws IOException  InetAddress address = InetAddress.getByName("time.nist.gov"); Socket socket = new Socket(address, 13); InputStream in = socket.getInputStream(); Scanner scanner = new Scanner(in); String response = scanner.nextLine(); int julianDate = Integer.parseInt(response.substring(1, 4)); int milliseconds = Integer.parseInt(response.substring(5, 10)); Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.YEAR, 2000); calendar.set(Calendar.DAY_OF_YEAR, julianDate); Date date = calendar.getTime(); date.setTime(date.getTime() + milliseconds); System.out.println(date); socket.close(); > >

This code will print the current time as reported by the time server. Note that the time returned by the server may not be exactly the same as the time on your local machine due to network latency and other factors.

Method 2: Using the java.util.TimeZone class

Here are the steps to get the time from an internet time server using the java.util.TimeZone class:

SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
  1. Create a URL object for the time server you want to use. In this example, we will use the time server provided by the National Institute of Standards and Technology (NIST).
URL url = new URL("https://nist.time.gov/actualtime.cgi");
URLConnection conn = url.openConnection();
InputStream in = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String data = reader.readLine();
Pattern pattern = Pattern.compile(".*\"time\":\"([^\"]+)\".*"); Matcher matcher = pattern.matcher(data); matcher.matches(); String time = matcher.group(1);
long timeInMillis = Long.parseLong(time) + 2208988800000L;
Date date = new Date(timeInMillis);
  1. Set the time zone for the SimpleDateFormat object using the setTimeZone() method of the java.util.TimeZone class.
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
String formattedDate = dateFormat.format(date);

Here is the complete code:

import java.io.*; import java.net.*; import java.text.*; import java.util.*; import java.util.regex.*; public class TimeClient  public static void main(String[] args) throws Exception  SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); URL url = new URL("https://nist.time.gov/actualtime.cgi"); URLConnection conn = url.openConnection(); conn.setReadTimeout(5000); InputStream in = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String data = reader.readLine(); Pattern pattern = Pattern.compile(".*\"time\":\"([^\"]+)\".*"); Matcher matcher = pattern.matcher(data); matcher.matches(); String time = matcher.group(1); long timeInMillis = Long.parseLong(time) + 2208988800000L; Date date = new Date(timeInMillis); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); String formattedDate = dateFormat.format(date); System.out.println("Time: " + formattedDate); > >

Method 3: Using the java.text.SimpleDateFormat class

To use an Internet time server to get the time in Java using the SimpleDateFormat class, you can follow these steps:

import java.net.URL; import java.net.URLConnection; import java.text.SimpleDateFormat; import java.util.Date;
URL url = new URL("http://www.example.com/time");
URLConnection conn = url.openConnection();
  1. Get the current time from the time server using the getInputStream() method of the URLConnection class:
long serverTime = conn.getInputStream().read();
Date date = new Date(serverTime);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = sdf.format(date);

Here’s the complete code example:

import java.net.URL; import java.net.URLConnection; import java.text.SimpleDateFormat; import java.util.Date; public class TimeClient  public static void main(String[] args) throws Exception  URL url = new URL("http://www.example.com/time"); URLConnection conn = url.openConnection(); long serverTime = conn.getInputStream().read(); Date date = new Date(serverTime); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String formattedDate = sdf.format(date); System.out.println("Server time: " + formattedDate); > >

This code will connect to the time server specified in the URL and retrieve the current time. It will then format the time using the SimpleDateFormat class and print it to the console. You can modify the date format in the SimpleDateFormat constructor to display the time in a different format.

Method 4: Using the org.joda.time.DateTime class

To use an Internet time server to get the time in Java, you can use the org.joda.time.DateTime class. Here are the steps to do it:

  1. Add the Joda-Time library to your project. You can download it from the Joda-Time website or use a dependency management tool like Maven or Gradle.
  2. Create a DateTimeZone object with the name of the time zone you want to get the time for. For example, if you want to get the time for the Eastern Standard Time zone, you can use:
DateTimeZone timeZone = DateTimeZone.forID("America/New_York");
  1. Create a DateTime object with the current time from an Internet time server. You can use the org.apache.commons.net.ntp.NTPUDPClient class from the Apache Commons Net library to get the time from an NTP server. Here’s an example:
NTPUDPClient client = new NTPUDPClient(); client.open(); TimeInfo info = client.getTime(InetAddress.getByName("pool.ntp.org")); long time = info.getReturnTime(); DateTime dateTime = new DateTime(time, timeZone);

This code gets the time from the NTP server at pool.ntp.org and creates a DateTime object with the returned time and the specified time zone.

  1. Use the DateTime object to get the date and time components as needed. For example, you can use the getYear() , getMonthOfYear() , getDayOfMonth() , getHourOfDay() , getMinuteOfHour() , and getSecondOfMinute() methods to get the individual components of the date and time.
int year = dateTime.getYear(); int month = dateTime.getMonthOfYear(); int day = dateTime.getDayOfMonth(); int hour = dateTime.getHourOfDay(); int minute = dateTime.getMinuteOfHour(); int second = dateTime.getSecondOfMinute();

That’s it! With these steps, you can use an Internet time server to get the time in Java using the org.joda.time.DateTime class.

Method 5: Using the java.time.Clock class

To use an Internet time server to get the time in Java, you can use the java.time.Clock class. Here are the steps to follow:

  1. Create an instance of java.time.Clock using the java.time.Clock.systemUTC() method. This clock will use the UTC time zone.
  2. Set the clock’s instant to the current time obtained from the internet time server using the java.time.Clock.fixed() method. This method takes an Instant object as a parameter.
  3. You can now use the java.time classes to work with the time obtained from the internet time server.

Here is an example code snippet:

import java.time.*; import java.net.*; import java.io.*; public class InternetTimeServerExample  public static void main(String[] args) throws IOException  // Create a URL object for the internet time server URL url = new URL("http://www.timeapi.org/utc/now"); // Open a connection to the URL URLConnection conn = url.openConnection(); // Get the input stream from the connection InputStream in = conn.getInputStream(); // Read the input stream into a string BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String response = reader.readLine(); // Parse the string into an Instant object Instant instant = Instant.parse(response); // Create a clock using the fixed instant from the internet time server Clock clock = Clock.fixed(instant, ZoneOffset.UTC); // Use the clock to get the current date and time LocalDateTime now = LocalDateTime.now(clock); // Print the current date and time System.out.println("Current date and time from internet time server: " + now); > >

In this example, we use the java.net.URL and java.net.URLConnection classes to open a connection to the internet time server and read the current time from it. We then use the java.time.Instant class to parse the response into an Instant object. Finally, we create a Clock object using the fixed() method with the Instant object from the internet time server, and use it to get the current date and time using the java.time.LocalDateTime class.

Источник

Читайте также:  Connection pooling java spring
Оцените статью