2011-06-10 56 views
3

我有问题,无法找到答案。我想用java测量互联网带宽,但我不知道如何。如何测量互联网带宽

这将是伟大的,得到一些提示;我知道我必须打开一个套接字并将其发送给定义的服务器,然后将其重新使用并使用时间。

但是,我会如何编码?

+0

你说的是由Java程序本身所使用的带宽? – 2011-06-10 21:13:33

回答

5

嗯,我只是通过下载一个固定大小的文件来实现这一点。未经测试,但沿着这些线路的东西应该工作得很好

byte[] buffer = new byte[BUFFERSIZE]; 
Socket s = new Socket(urlOfKnownFile); 
InputStream is = s.getInputStream(); 
long start = System.nanoTime(); 
while (is.read(buffer) != -1) continue; 
long end = System.nanoTime(); 
long time = end-start; 
// Now we know that it took about time ns to download <filesize>. 
// If you don't know the correct filesize you can obviously use the total of all is.read() calls. 
1

如何修复任意时间量并发送有关它的数据?

例如,假设我希望我的服务器将其带宽使用限制为100Bytes/s。 所以我修正1秒,并发送数据,只要它不超过1秒和100字节。

下面是一些伪代码显示什么我谈论:

timer_get (a); 
sent_data = 0; 

while (not_finished_sending_data) 
{ 
    timer_get (b); 
    if ((b - a) < 1) // 1 second 
    { 
     if (sent_data < 100) // 100 bytes 
     { 
      // We actually send here 
      sent_data += send(); 
     } 
    } 
    else 
    { 
     timer_get (a); 
     sent_data = 0; 
    } 
}