0

Below is the code for implementing time server

Server class

public static void main(String args[])
    {
   try{
            ServerSocket ss=new ServerSocket(990);
             Socket s=ss.accept();
            while(true)
            {
                Calendar c=Calendar.getInstance();
                BufferedReader in=new BufferedReader(new InputStreamReader(s.getInputStream()));
                PrintWriter out =new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
                out.println("Hello This is server & My Time is :");
                out.println("Time :::  Hour="+c.HOUR +" Min="+c.MINUTE +" sec="+c.SECOND);
            out.flush();
              s.close();
            }
        }
        catch(Exception e)
        {
        }
    }

Client class

public static void main(String args[])
    {
   try{
            ServerSocket ss=new ServerSocket(990);
             Socket s=ss.accept();
            while(true)
            {
                Calendar c=Calendar.getInstance();
                BufferedReader in=new BufferedReader(new InputStreamReader(s.getInputStream()));
                PrintWriter out =new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
                out.println("Hello This is server & My Time is :");
                out.println("Time :::  Hour="+c.HOUR +" Min="+c.MINUTE +" sec="+c.SECOND);
            out.flush();
              s.close();
            }
        }
        catch(Exception e)
        {
        }
    }

the program is working but the output is always

time:: hour=10 min=12 sec=13

why it is outputting the above values

karan
  • 8,637
  • 3
  • 41
  • 78

1 Answers1

5

That's because you're printing the values of the static integer fields called HOUR, MINUTE, SECOND present in the Calendar class. You need to use the Calendar#get(field) method to get the HOUR, MINUTE, SECOND values from the Calendar.

out.println("Time :::  Hour="+c.get(Calendar.HOUR) +" Min="+c.get(Calendar.MINUTE)+" sec="+c.get(Calendar.SECOND));

Note that since HOUR, MINUTE, SECOND are static fields, you need to access them using the class name(Calendar.SECOND) and not using the instance(c.SECOND).

Rahul
  • 44,383
  • 11
  • 84
  • 103
  • getting the current time is not an issue, i did that with c.gettime() and simpledateformat, but i only want to know even though i have not assigned values to them why are they printing 10,12 and 13 everytime? – karan Feb 19 '14 at 07:02
  • They are assigned. Calendar.HOUR is an Integer with the value 10. – Alexander_Winter Feb 19 '14 at 07:04
  • 1
    That's because `HOUR` is a static integer field already present in the Calendar class. And the value for that is `10` and the same goes for `MINUTE` and `SECOND`. You shouldn't mistake the Calendar fields with the actual hour, minute and second data. – Rahul Feb 19 '14 at 07:04