Faced with the following problem:
I need to determine bandwidth for a given ip and depending on it my task will be done in different ways.
I've written a simple implementation
Client:
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();
}
Server:
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);
}
}
Test class:
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);
}
The problem is that using different sizes of the input files I get different speeds. Tell me, please, how to solve this problem.
The problem is the TCP slow-start. http://en.wikipedia.org/wiki/Slow-start
Try to first transfer something like 10KBs, followed by the real measurement transfer. Make sure to use the same connection for both transfers.