如何使用 Java 检测 Internet 连接速度? [英] How to detect Internet connection speed with Java?

查看:28
本文介绍了如何使用 Java 检测 Internet 连接速度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 Java 应用程序中,我如何检测 Internet 连接速度有多快?例如,我在家里使用 AT&T Fast DSL,我想知道是否可以编写一个方法来执行以下操作:

In my Java app, how do I detect how fast the Internet connection speed is ? For instance, I use AT&T Fast DSL at home, I wonder if there is a way I can write a method that does the following :

int getInternetConnectionSpeed()
{
   ...
}

这将返回一个以 kbps 为单位的数字,例如 2800kbps [ 2.8 M ]

Which will return a number in kbps, something like 2800kbps [ 2.8 M ]

我问的原因是在我的应用程序中,我可以打开多个 Internet 流,这取决于用户的 Internet 连接速度,我希望它自动确定打开多少流而不阻塞应用程序.

Edit : The reason I'm asking, is in my app, I can open multiple Internet streams, depending on the users' Internet connection speed, I want it to auto determine how many streams to open without chocking the app.

推荐答案

我认为您可能以错误的方式思考问题.拍摄连接速度的快照仅表明它们在该时刻的吞吐量.当您运行占用他们带宽的测试时,他们很容易运行另一个应用程序,然后您的测量值一文不值.

I think that you could be thinking about the problem in the wrong way. Taking a snapshot of a connection speed is only an indication of their throughput at that instant in time. They could quite easily be running another application when you run test that sucks their bandwidth and then your measured values are worthless.

相反,我认为您应该不断地添加或删除线程,具体取决于它是增加还是减少它们的吞吐量.我建议这样的事情(仅限伪代码):

Instead, I think you should be constantly adding or removing threads depending on whether it increases or decreases their throughput. I'd suggest something like this (pseudo code only):

while(true) {
  double speedBeforeAdding = getCurrentSpeed();
  addThread();
  // Wait for speed to stabilise
  sleep(20 seconds);
  double speedAfterAdding = getCurrentSpeed();
  if(speedAfterAdding < speedBeforeAdding) {
    // Undo the addition of the new thread
    removeThread();
    // Wait for speed to stabilise
    sleep(20 seconds);

    if(getNumberOfThreads() > 1) {
      double speedBeforeRemoving = getCurrentSpeed();
      // Remove a thread because maybe there's too many
      removeThread();
      // Wait for speed to stabilise
      sleep(20 seconds);
      double speedAfterRemoving = getCurrentSpeed();
      if(speedAfterRemoving < speedBeforeRemoving) {
        // Add the thread back
        addThread();
        // Wait for speed to stabilise
        sleep(20 seconds);
      }
    }
  }
}

您可以调整适合的睡眠时间.我在这里假设 getCurrentSpeed() 返回 all 下载线程的吞吐量,并且您能够在应用程序执行期间动态打开和关闭线程.

You can fiddle with the sleep timings to suit. I'm assuming here that getCurrentSpeed() returns the throughput of all download threads and that you're able to dynamically open and close threads during your application's execution.

这篇关于如何使用 Java 检测 Internet 连接速度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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