0

I am trying to limit the amount of data transmitted through an URLConnection per second. I implemented a wrapper for InputStreams and OutputStreams, as well as for sockets that utilize these streams. Next I created a custom SocketFactory that provides the limited sockets. But now the problem is that I dont know how I can set up an URLConnection that uses my SocketFactory. Do you have any ideas how to realise that?

One way would be to change the URLConnetions to use my throttled streams but it would be great to access the socket used by the URLConnection itself.

1 Answers1

0

hi this is related to another question : How can I limit bandwidth in Java?

This solution is easy and works fine for me.

//SERVER CODE

    Stream in;
long timestamp = System.currentTimeInMillis();
int counter = 0;
int INTERVAL = 1000; // one second
int LIMIT = 1000; // bytes per INTERVAL

...

/**
 * Read one byte with rate limiting
 */
@Override
public int read() {
    if (counter > LIMIT) {
        long now = System.currentTimeInMillis();
        if (timestamp + INTERVAL >= now) {
            Thread.sleep(timestamp + INTERVAL - now);  
        }
        timestamp = now;
        counter = 0;
    }
    int res = in.read();
    if (res >= 0) {
        counter++;
    }
    return res;
}

//CLIENT CODE

 URL oracle = new URL("http://www.oracle.com/");
        URLConnection yc = oracle.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(
                                    yc.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) 
            System.out.println(inputLine);
        in.close();

source of client code : https://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html

Community
  • 1
  • 1
jeorfevre
  • 2,286
  • 1
  • 17
  • 27
  • I found that thread as well. It helped me to implement limited streams and sockets. But now i need to know how tu use these sockets in an URLConnection. – CitizenVayne Apr 03 '16 at 11:19
  • Yes, I am on the client side. I could use the code you provided to create an URLConnection with limited data per timeframe. Still it would be good if i can adress the underlying socket directly somehow. I intended to change the allocated buffer size for sending and receiving on the socket. – CitizenVayne Apr 03 '16 at 11:37