简体   繁体   English

如何通过 Socket 找到 HTTP 请求的响应时间

[英]How can I find the response time of a HTTP request through a Socket

I'm using a Java socket, connected to a server.我正在使用连接到服务器的 Java 套接字。 If I send a HEADER http request, how can I measure the response time from the server?如果我发送 HEADER http 请求,如何测量服务器的响应时间? Must I use a provided java timer, or is there an easier way?我必须使用提供的 java 计时器,还是有更简单的方法?

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.请人们,仅限代码中的解决方案。

curl -s -w "%{time_total}\\n" -o /dev/null http://server:3000

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?还是您只想测量服务器端时间?

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.否则,由于您是通过 Socket 自己管理请求,您可以通过检查系统计时器并计算差异来测量任意两个时刻之间经过的时间。 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).此代码将测量从您开始写出请求到完成接收响应的时间,并打印结果(假设您实现了特定的读/写方法)。

You can use time and curl and time on the command-line.您可以在命令行上使用 time 和 curl 和 time。 The -I argument for curl instructs it to only request the header. curl 的 -I 参数指示它仅请求标头。

time curl -I 'http://server:3000'

Something like this might do the trick像这样的事情可能会奏效

import java.io.IOException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.methods.HeadMethod;
import org.apache.commons.lang.time.StopWatch;
//import org.apache.commons.lang3.time.StopWatch

public class Main {

    public static void main(String[] args) throws URIException {
        StopWatch watch = new StopWatch();
        HttpClient client = new HttpClient();
        HttpMethod method = new HeadMethod("http://stackoverflow.com/");
        
        try {
            watch.start();
            client.executeMethod(method);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            watch.stop();
        }
        
        System.out.println(String.format("%s %s %d: %s", method.getName(), method.getURI(), method.getStatusCode(), watch.toString()));
        
    }
}
HEAD http://stackoverflow.com/ 200: 0:00:00.404

Maybe I'm missing something, but why don't you just use:也许我错过了一些东西,但你为什么不直接使用:

// open your connection
long start = System.currentTimeMillis();
// send request, wait for response (the simple socket calls are all blocking)
long end = System.currentTimeMillis();
System.out.println("Round trip response time = " + (end-start) + " millis");
@Aspect
@Profile("performance")
@Component
public class MethodsExecutionPerformance {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Pointcut("execution(* it.test.microservice.myService.service.*.*(..))")
    public void serviceMethods() {
    }

    @Around("serviceMethods()")
    public Object monitorPerformance(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        StopWatch stopWatch = new StopWatch(getClass().getName());
        stopWatch.start();
        Object output = proceedingJoinPoint.proceed();
        stopWatch.stop();
        logger.info("Method execution time\n{}", stopWatch.prettyPrint());
        return output;
    }
}

In this way, you can calculate the real response time of your service independent of network speed.通过这种方式,您可以独立于网络速度计算服务的实际响应时间。

使用 AOP 拦截对套接字的调用并测量响应时间。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何通过Java中的套接字获取HTTP响应? - How to get HTTP response through socket in java? 如何使用 JAVA 中的 HTTP 请求通过 TCP 套接字获取网页 - How to Fetch Webpage Through TCP socket using HTTP Request in JAVA 套接字http请求tomcat,但响应302 - socket http request to tomcat, but response 302 我如何发出HTTP POST请求并使用我应该在android中获得的Json响应 - How can i make an HTTP POST request and and use the Json Response i should get in android 为什么在通过TCP套接字发送手动制作的HTTP请求时,我收到HTTP 400错误的请求响应? - Why am I getting a HTTP 400 bad request response when sending a manually-crafted HTTP request over a TCP socket? 来自套接字的Java HTTP请求/响应,服务器在客户端可以接收之前关闭输出流 - Java HTTP request/response from socket, server closing output stream before client can recieve 如何在没有 BufferedReader 的情况下从 Java 中的 http get 请求中检索响应 - How can I retrieve the response from an http get request in Java WITHOUT BufferedReader 如何让Jetty返回错误响应,而不是假设HTTP / 0.9请求? - How can I get Jetty to return an error response instead of assuming an HTTP/0.9 request? 如何从日志中提取带有 Http 响应 200 的 GET 请求请求的 gif 文件? - How can I extract the gif files requested by a GET request with Http response 200 from a log? 当 java 中的请求失败时,如何获取 http 响应正文? - How can I get http response body when request is failed in java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM