【问题标题】:Bandwidth speed testing带宽速度测试
【发布时间】:2014-05-21 00:37:51
【问题描述】:

面临以下问题:

我需要确定给定 ip 的带宽,根据它,我的任务将以不同的方式完成。

我写了一个简单的实现

客户:

public void send(Socket socket, File file) throws IOException {

    FileInputStream inputStream = null;
    DataOutputStream outputStream = null;

    try {
        inputStream = new FileInputStream(file);
        int fileSize = (int) file.length();

        byte[] buffer = new byte[fileSize];

        outputStream = new DataOutputStream(socket.getOutputStream());

        outputStream.writeUTF(file.getName());

        int recievedBytesCount = -1;

        while ((recievedBytesCount = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, recievedBytesCount);
        }
    } catch (IOException e) {
        System.out.println(e);
    } finally {
        inputStream.close();
        outputStream.close();
        socket.close();
    }

服务器:

    public void recieve() throws IOException {

    ServerSocket server = new ServerSocket (port);
    Socket client = server.accept();

    DataInputStream dataInputStream = new DataInputStream(client.getInputStream());
    DataInputStream inputStream = new DataInputStream(client.getInputStream());

    String fileName = dataInputStream.readUTF();

    FileOutputStream fout = new FileOutputStream("D:/temp/" + fileName);

    byte[] buffer = new byte[65535];

    int totalLength = 0;
    int currentLength = -1;

    while((currentLength = inputStream.read(buffer)) != -1){
        totalLength += currentLength;
        fout.write(buffer, 0, currentLength);
    }
}

测试类:

public static void main(String[] args) {

        File file = new File("D:\\temp2\\absf.txt");
        Socket socket = null;
        try {
            socket = new Socket("127.0.0.1", 8080);
        } catch (IOException e) {
            e.printStackTrace();
        }

        ClientForTransfer cl = new ClientForTransfer();

        long lBegin = 0;
        long lEnd = 0;

        try {
            lBegin = System.nanoTime();
            cl.send(socket, file);
            lEnd = System.nanoTime();
        } catch (IOException e) {
            e.printStackTrace();
        }

        long lDelta = lEnd - lBegin;

        Double result =  ( file.length() / 1024.0 / 1024.0 * 8.0 / lDelta * 1e-9 );      //Mbit/s

        System.out.println(result);

    }

问题是使用不同大小的输入文件我得到不同的速度。 请告诉我,如何解决这个问题。

【问题讨论】:

标签: java tcp file-transfer bandwidth


【解决方案1】:

问题是 TCP 启动缓慢。 http://en.wikipedia.org/wiki/Slow-start

尝试首先传输 10KB 之类的数据,然后进行实际测量传输。确保两次传输使用相同的连接。

【讨论】:

    【解决方案2】:

    这不是一个容易“解决”的问题。为不同大小的文件获得不同的速度是完全正常的,因为“带宽”取决于很多很多因素,包括原始连接速度、质量(丢弃的数据包)和延迟,甚至会随时变化。

    您需要尝试几种不同的文件大小,从小文件开始,然后移动到较大的文件,直到传输需要 10-20 秒才能判断平均带宽。

    【讨论】:

      猜你喜欢
      • 2017-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多