大家好:      我写了这样一段程序连接某个服务器的80端口;
    public static void main(String[] args) throws Exception{
        Socket socket = new Socket("server",80);
        String data = "GET index.html HTTP/1.1\r\n\r\n";
        socket.getOutputStream().write(data.getBytes(),0,data.length()); 
        socket.getOutputStream().flush(); 
        Date d = new Date();
        System.out.println(d.toString());
        StringBuffer sb = new StringBuffer();
        while(socket.getInputStream().available()==0);
        int c;
        while ((c = socket.getInputStream().read()) != -1)
            sb.append((char) c);
        System.out.println(sb.toString());
        d = new Date();
        System.out.println(d.toString());
        System.out.println("done");
    }
结果服务器隔了三分钟才有response,但是如果用windows自带的telnet连接上去,
打"GET index.html HTTP/1.1"接两个回车,则马上就有response显示出来。请问这个延迟问题应该怎么解决?多谢帮助!

解决方案 »

  1.   

    三分钟,太夸张了吧?
    是不是server解析有问题,换成IP地址看看速度如何?
      

  2.   

    我在连接之前和之后用Date计时的,的确花了三分钟左右。如果说是域名解析的问题,为什么用windows自带的telnet连上去就没有延时呢?
      

  3.   

    程序本身应该没什么问题吧,测试过几个域名,只要能连上的都没有什么延迟:),不能连的就久一些
        public static void main(String[] args) throws Exception{
            Socket socket = new Socket("www.google.com",80);
            String data = "GET /intl/zh-CN/ HTTP/1.1\r\n\r\n";
            socket.getOutputStream().write(data.getBytes(),0,data.length()); 
            socket.getOutputStream().flush(); 
            
            long start = System.currentTimeMillis();
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                boolean more = true;
                
                while (more){
                    String line = in.readLine();
                    
                    if (line == null)
                        more = false;
                    else
                        System.out.println(line);
                }
            
            long end  = System.currentTimeMillis();
            System.out.println("耗时:" + (end - start) + "毫秒");
        }