如何通过套接字找到HTTP请求的响应时间 [英] How can I find the response time of a HTTP request through a Socket

查看:98
本文介绍了如何通过套接字找到HTTP请求的响应时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用连接到服务器的Java套接字. 如果发送HEADER http请求,如何测量服务器的响应时间?我必须使用提供的Java计时器,还是有更简单的方法?

I'm using a Java socket, connected to a server. If I send a HEADER http request, how can I measure the response time from the server? Must I use a provided java timer, or is there an easier way?

我正在寻找一个简短的答案,我不想使用其他协议等.显然,我也不想拥有将我的应用程序绑定到特定OS的解决方案.拜托大家,仅IN-CODE解决方案.

I'm looking for a short answer, I don't want to use other protocols etc. Obviously do I neither want to have a solution that ties my application to a specific OS. Please people, IN-CODE solutions only.

推荐答案

我要说的是,这取决于您尝试测量的确切间隔,即从发送请求的最后一个字节到请求的第一个字节所花费的时间.您收到的回复?还是直到收到整个答复?还是您只想衡量服务器端时间?

I would say it depends on what exact interval you are trying measure, the amount of time from the last byte of the request that you send until the first byte of the response that you receive? Or until the entire response is received? Or are you trying to measure the server-side time only?

如果您只想衡量服务器端的处理时间,那么将很难计算出要请求到达和返回响应所花费的网络传输时间.否则,由于您是通过Socket自己管理请求,因此可以通过检查系统计时器并计算差值来测量任意两个时刻之间的经过时间.例如:

If you're trying to measure the server side processing time only, you're going to have a difficult time factoring out the amount of time spent in network transit for your request to arrive and the response to return. Otherwise, since you're managing the request yourself through a Socket, you can measure the elapsed time between any two moments by checking the System timer and computing the difference. For example:

public void sendHttpRequest(byte[] requestData, Socket connection) {
    long startTime = System.nanoTime();
    writeYourRequestData(connection.getOutputStream(), requestData);
    byte[] responseData = readYourResponseData(connection.getInputStream());
    long elapsedTime = System.nanoTime() - startTime;
    System.out.println("Total elapsed http request/response time in nanoseconds: " + elapsedTime);
}

这段代码将测量从您开始写请求到完成接收响应的时间,并打印结果(假设您已实现特定的读/写方法).

This code would measure the time from when you begin writing out your request to when you finish receiving the response, and print the result (assuming you have your specific read/write methods implemented).

这篇关于如何通过套接字找到HTTP请求的响应时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆