Java:套接字编程示例

时间:2010-10-17 05:28:41

标签: java sockets network-programming compiler-errors quotes

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

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 个答案:

答案 0 :(得分:5)

引号应为"而不是。也就是说,你应该

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

而不是

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

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

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

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

这大致是我写的方式

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

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

答案 1 :(得分:2)

你需要使用双引号(")来包围字符串,看起来你使用的是倒置引号:

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

答案 2 :(得分:0)

这个例子可能有所帮助 https://github.com/bitsabhi/DemoChatApp 服务器端的User ServerSocket和Android客户端的Socket