Reputation: 8853
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
Upvotes: 0
Views: 67
Reputation: 45070
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
).
Upvotes: 5