首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

限制下传和上载

2012-12-24 
限制上传和下载不多说了,自己看吧public class FlowControlOutputStream extends FilterOutputStream {pri

限制上传和下载
不多说了,自己看吧

public class FlowControlOutputStream extends FilterOutputStream {    private long timestamp;    private int maxbps;    private int currentbps;    private int byteswrite;public FlowControlOutputStream(OutputStream out, int maxbps) {super(out);        this.maxbps = maxbps;        this.currentbps = 0;        this.byteswrite = 0;        this.timestamp = System.currentTimeMillis();}public void setMaxbps(int maxbps){this.maxbps = maxbps;}@Overridepublic void write(int oneByte) throws IOException {        synchronized(out){            int avaliable = check();            if(avaliable <= 0){                waitForAvailable();            }            out.write(oneByte);            update(1);        }}@Overridepublic void write(byte[] buffer) throws IOException {write(buffer, 0, buffer.length);}@Overridepublic void write(byte[] buffer, int offset, int length) throws IOException { synchronized(out){            int avaliable = check();            if(avaliable <= 0){                waitForAvailable();            }            out.write(buffer, offset, length);            update(length); }}    private int check(){        long now = System.currentTimeMillis();        if(now - timestamp >= 1000){            timestamp = now;            currentbps = byteswrite;            byteswrite = 0;            return maxbps;        }else{            return maxbps - byteswrite;        }    }     private void waitForAvailable(){        long time = System.currentTimeMillis() - timestamp;        boolean isInterrupted = false;        while(time < 1000){            try{                Thread.sleep(1000 - time);            }catch(InterruptedException e){                isInterrupted = true;            }            time = System.currentTimeMillis() - timestamp;        }        if(isInterrupted)            Thread.currentThread().interrupt();        return;            }     private void update(int n){        byteswrite += n;    }        public int getCurrentbps(){        return currentbps;    }}

热点排行