package com.nms.server.util.socket.limiter;

import java.io.IOException;
import java.io.InputStream;

import com.nms.server.util.socket.SocketUtils;


/**
 *  封装InputStream 引入BandwidthLimiter实现带宽限制
 *  @date Nov 15, 2012 10:47:18 AM
 *	@author ZhangGang
 *
 */
public class InputStreamLimiter extends InputStream {
	
	private InputStream is = null;
	
	/* 设定最小数据包长度，最大限度实现数据读取平均化，降低通讯幅度峰值 */
	private final int BUFF_SIZE =  SocketUtils.BUFF_SIZE;
	
	/**
	 * 构造函数封装InputStream
	 * 引入BandwidthLimiter的IO计数器 创建：加1
	 * @param is InputStream
	 */
	public InputStreamLimiter(InputStream is) {
		this.is = is;
		BandwidthLimiter.addLink();
	}
	
	@Override
	public int read() throws IOException {
		BandwidthLimiter.limitNextBytes();
		return this.is.read();
	}

	/** 
	 * 重构read(byte[], int, int)方法
	 * 将 b[] 切分数据包到最小数据包读取数据
	 * 引入BandwidthLimiter限速方法
	 * @see java.io.InputStream#read(byte[], int, int)
	 */
	public  int read(byte b[], int off, int len) throws IOException {
		
		int len2 = 0;
	
	    int c=-1;
		while(len>0){
			int p = len<BUFF_SIZE? len:BUFF_SIZE;

			c = this.is.read(b, off, p);
			//System.out.println(" limiter "+c);
			off  += c;
			len2 += c;
			len -= p;
			BandwidthLimiter.limitNextBytes(c);
			if(c<p){break;}
		}
		
		return len2;
	}
	/** 
	 * 关闭IO流
	 * 重写父方法，引入BandwidthLimiter的IO计数器 关闭：减1
	 * @see java.io.InputStream#close()
	 */
	public void close() throws IOException{
		BandwidthLimiter.removeLink();
		this.is.close();
	}
	
	/*public static void main(String [] args){
		FileInputStream stream = null;
		try {
			File file = new File("D:/logfile.txt.bak");
			stream = new FileInputStream(file);
			InputStreamLimiter limiter = new InputStreamLimiter(stream);
			long longs = file.length();
			System.out.println(""+longs);
			byte[] bytes = new byte[1024];
			int n = 0;
			while((n = limiter.read(bytes))>0){
				System.out.println("-- "+n);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				if(stream!=null)stream.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}*/
}