Display server date & time on client - Java

Q. Write a client-server program which displays the server machine's date and time on the client machine.

Answer:

In this example both client and server program run on different command prompt. The time and date of server machine's is displayed on client machine.

DateClient.java

import java.io.*;
import java.net.*;
class DateClient
{
    public static void main(String args[]) throws Exception
    {
        Socket soc=new Socket(InetAddress.getLocalHost(),5217);        
        BufferedReader in=new BufferedReader(new InputStreamReader(soc.getInputStream()  ));
        System.out.println(in.readLine());
    }    
}


DateServer.java

import java.net.*;
import java.io.*;
import java.util.*;
class DateServer
{
    public static void main(String args[]) throws Exception
    {
        ServerSocket s=new ServerSocket(5217);
        while(true)
        {
            System.out.println("Waiting For Connection ...");
            Socket soc=s.accept();
            DataOutputStream out=new DataOutputStream(soc.getOutputStream());
            out.writeBytes("Server Date: " + (new Date()).toString() + "\n");
            out.close();
            soc.close();
        }
    }
}


Output:

  • First compile the client code on console and then compile the server code on different console.
  • Run the server code, after that client code. Now the client console shows the time and date of server machine.
Server Date: Fri Dec 16 17:05:42 IST 2016