How to measure response-time of network using Java?

时间秒杀一切 提交于 2019-12-22 07:58:17

问题


We have a client and a server. I want to measure the response-time of the network between them. When I send a request to server it should immediate respond to my request, it should be like a ping request so that there will be no processing time at the server.

How can I do this in Java?


回答1:


I have done this by sending a packet with a timestamp from client to server, and then having the server return the same timestamp back. When the server receives the timestamp, it can compare against the current timestamp to measure round trip time.

Apparently there is a way to generate an ICMP ping in Java 5 and later. If you want to measure network speeds, just grab System.nanoTime() before and after and compare. Note that if your program is running with insufficient privs to do ICMP ping, then Java will resort to using a TCP echo request to port 7, which will still suit your needs.




回答2:


To ensure that the server response as fast as possible, you should either

  1. have a second connection to a different port - this is useful if you want to test the route to the server, i.e. the wires - or
  2. a common thread for all incoming packets, that will decide whether an incoming packet is a ping request and respond immediately - which is useful if you want to test the current connection (which takes other packets on that connection into account).

Either way the listening part (server) should have its own Thread or the processing of the request could stale while other packets are being processed.

Note that, whatever you do to measure the speed of the connection, you will not have a reliable value. You should have an acceptable value, though, if you take the average of several such pings.




回答3:


I think you need to distinguish between the time taken to the server (machine), and the time for your server-side process to handle this. For example, ping will simply measure the ICMP response time, which is a low-level network protocol return. If you take into account the TCP stack, and then the subsequent processing by the server, that time period will be greater.

From your question, it sounds like ping (ICMP) is what you want. In JDK 5 and above, you can do:

String host = "192.168.0.1"
int timeOut = 5000; 
boolean status = InetAddress.getByName(host).isReachable(timeOut)

and you would need to time that using System.nano() or similar.




回答4:


using ping should be enough or wget that trace transfer rate. You can use justniffer for sniffing response times of "production" running servers.



来源:https://stackoverflow.com/questions/724124/how-to-measure-response-time-of-network-using-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!