gpt4 book ai didi

java - 带宽速度测试

转载 作者:行者123 更新时间:2023-12-01 12:57:28 26 4
gpt4 key购买 nike

面临以下问题:

我需要确定给定 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);

}

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

最佳答案

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

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

关于java - 带宽速度测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23764826/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com