小木屑 2014-10-31 07:23 采纳率: 0%
浏览 1123

关于Socket中的输出流缓存问题

为什么以下程序中Send Request cost的输出在第二次之后都是0或者1ms?
public class MyThread implements Runnable {
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
getTime();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void getTime() {
String strServer = "www.baidu.com";
Socket socket = null;
try {
int port = 80;
InetAddress addr = InetAddress.getByName(strServer);
long time3 = System.currentTimeMillis();
socket = new Socket(addr, port);
long time4 = System.currentTimeMillis();
System.out.println("Connect cost:" + (time4 - time3) + "ms");
long time5 = System.currentTimeMillis();
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
wr.write("GET / HTTP/1.0\r\n");
wr.write("HOST: www.baidu.com\r\n");
wr.write("Accept:*/*\r\n");
wr.write("\r\n");
wr.flush();
long time6 = System.currentTimeMillis();
System.out.println("Send Request cost:" + (time6 - time5)+ "ms");
wr.close();

    } catch (Exception e) {
        System.out.println("Website not access");
        e.printStackTrace();
    }
}

public static void main(String[] args) throws InterruptedException {
    MyThread s = new MyThread();
    new Thread(s).start();
}

}

  • 写回答

1条回答 默认 最新

  • CSDN-Ada助手 CSDN-AI 官方账号 2022-10-25 19:35
    关注
    不知道你这个问题是否已经解决, 如果还没有解决的话:

    如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^
    评论

报告相同问题?

悬赏问题

  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试