Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding server internet bandwidth thru java for streaming

Following this thread. Streaming large files in a java servlet.

Is it possible to find the total internet bandwidth available in current machine thru java?

what i am trying to do is while streaming large files thru servlet, based on the number of parallel request and the total band width i am trying to reduce the BUFFER_SIZE of the stream for each request. make sense?

Is there any pure java way? (without JNI)

like image 407
Madhu Avatar asked Feb 26 '26 03:02

Madhu


1 Answers

Maybe you can time how long the app need to send one package (the buffer). And if that is larger than x milliseconds, then make your buffer smaller. You can use other values for the original bufferSize and if (stop - start > 700).

This is based on the thread you noticed:

ServletOutputStream out = response.getOutputStream();
InputStream in = [ code to get source input stream ];
String mimeType = [ code to get mimetype of data to be served ];
int bufferSize = 1024 * 4;
byte[] bytes = new byte[bufferSize];
int bytesRead;

response.setContentType(mimeType);

while ((bytesRead = in.read(bytes)) != -1) {
    long start = System.currentTimeMillis();
    out.write(bytes, 0, bytesRead);
    long stop = System.currentTimeMillis();
    if (stop - start > 700)
    {
        bufferSize /= 2;
        bytes = new byte[bufferSize];
    }
}

// do the following in a finally block:
in.close();
out.close();
like image 129
Martijn Courteaux Avatar answered Feb 28 '26 17:02

Martijn Courteaux