views:

46

answers:

2

What is wrong with the following program to fetch time from time server.

public class SocketTest
{  
    public static void main(String[] args)
    {
         Socket s = new Socket(“time-A.timefreq.bldrdoc.gov”, 13);
          BufferedReader in = new BufferedReader(
                  new InputStreamReader(s.getInputStream()));
       String line;
       do
       {    line = in.readLine();  //read line of text from socket
              if (line != null)  System.out.println(line);
       }
       while(line != null);
    }

}
+3  A: 

The quotation-marks should be " instead of . That is, you should have

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

rather than

Socket s = new Socket(“time-A.timefreq.bldrdoc.gov”, 13);

Also, you'll need to encapsulate the IO operations in a try/catch block, or declare the method to throw IOException.

Other than that I don't have much complaints. If you import the classes properly, it will print something like

55486 10-10-17 05:30:44 22 0 0 604.7 UTC(NIST) * 

This is roughly how I would have written it

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

public class SocketTest {
    public static void main(String[] args) {
        try {
            Socket s = new Socket("time-A.timefreq.bldrdoc.gov", 13);
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    s.getInputStream()));
            String line;
            while ((line = in.readLine()) != null)
                System.out.println(line);

            s.close();
        } catch (IOException ioex) {
            ioex.printStackTrace();
        }
    }
}

Put the s.close() inside a finally block if you're picky and the program is larger than just a test-program like this one.

aioobe
oops! thanks @aioobe
rohit
s.close() should probably be inside the finally block.
Juha Syrjälä
Yes, I agree. :-)
aioobe
+1  A: 

You need to use double quotes (") to enclose the strings, looks like you are using inverted quotes:

new Socket(“time-A.timefreq.bldrdoc.gov”, 13);
           ^                           ^
codaddict