Java:套接字编程示例

roh*_*hit 2 java sockets quotes network-programming compiler-errors

以下程序从时间服务器获取时间有什么问题.

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);
    }

}
Run Code Online (Sandbox Code Playgroud)

aio*_*obe 5

引号应该"代替.也就是说,你应该拥有

Socket s = new Socket("time-A.timefreq.bldrdoc.gov", 13);
Run Code Online (Sandbox Code Playgroud)

而不是

Socket s = new Socket(“time-A.timefreq.bldrdoc.gov”, 13);
Run Code Online (Sandbox Code Playgroud)

此外,您需要将IO操作封装在try/catch块中,或者声明该方法抛出IOException.

除此之外我没有太多抱怨.如果正确导入类,它将打印出类似的内容

55486 10-10-17 05:30:44 22 0 0 604.7 UTC(NIST) * 
Run Code Online (Sandbox Code Playgroud)

这大致是我写的方式

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果你挑剔并且程序大于这样的测试程序,那么将s.close()放在finally块中.