【问题标题】:Implement limited bandwith for an URLConnection为 URLConnection 实现有限带宽
【发布时间】:2016-04-03 10:48:30
【问题描述】:

我试图限制每秒通过URLConnection 传输的数据量。我为InputStreams 和OutputStreams 以及使用这些流的套接字实现了一个包装器。接下来,我创建了一个自定义 SocketFactory,它提供了有限的套接字。但现在的问题是我不知道如何设置一个使用我的SocketFactoryURLConnection。您对如何实现这一点有任何想法吗?

一种方法是更改​​URLConnetions 以使用我的限制流,但最好访问URLConnection 本身使用的套接字。

【问题讨论】:

    标签: java network-programming


    【解决方案1】:

    您好,这与另一个问题有关:How can I limit bandwidth in Java?

    这个解决方案很简单,对我来说效果很好。

    //服务器代码

        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;
    }
    

    //客户代码

     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();
    

    客户端代码来源:https://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html

    【讨论】:

    • 我也找到了那个帖子。它帮助我实现了有限的流和套接字。但现在我需要知道如何在 URLConnection 中使用这些套接字。
    • 是的,我在客户端。我可以使用您提供的代码来创建每个时间范围内数据有限的 URLConnection。如果我能以某种方式直接寻址底层套接字仍然会很好。我打算更改为在套接字上发送和接收分配的缓冲区大小。
    猜你喜欢
    • 2012-04-20
    • 2012-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-21
    • 1970-01-01
    • 1970-01-01
    • 2021-03-27
    相关资源
    最近更新 更多