问题描述
- 关于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.0rn");
wr.write("HOST: www.baidu.comrn");
wr.write("Accept:*/*rn");
wr.write("rn");
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(); }
}
时间: 2024-11-02 01:11:49