面临以下问题:
我需要确定给定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);
}问题是,使用不同大小的输入文件,我得到不同的速度。请告诉我,如何解决这个问题。
发布于 2014-05-20 16:10:15
问题是TCP启动缓慢。http://en.wikipedia.org/wiki/Slow-start
试着先转移像10 to这样的东西,然后是真正的测量转移。确保对两种传输都使用相同的连接。
发布于 2014-05-20 16:12:49
这不是一个容易“解决”的问题。对于不同大小的文件,获得不同的速度是完全正常的,因为“带宽”取决于许多因素,包括原始连接速度、质量(丢弃的数据包)和延迟,甚至可能随时发生变化。
您需要尝试几个不同的文件大小,从小文件开始移动到更大的文件,直到传输需要10-20秒才能判断平均带宽。
https://stackoverflow.com/questions/23764826
复制相似问题