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

import java.io.IOException;
import java.io.OutputStream;

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

/**
 *  封装OutputStream 引入BandwidthLimiter实现带宽限制
 *  @date Nov 15, 2012 10:47:18 AM
 *	@author ZhangGang
 *
 */
public class OutputStreamLimiter extends OutputStream {
	
	private OutputStream os = null;
	
	/* 设定最小数据包长度，最大限度实现数据读取平均化，降低通讯幅度峰值 */
	private final int BUFF_SIZE =  SocketUtils.BUFF_SIZE;
	
	/**
	 * 构造函数封装OutputStream
	 * 引入BandwidthLimiter的IO计数器 创建：加1
	 * @param os OutputStream
	 */
	public OutputStreamLimiter(OutputStream os) {
		this.os = os;
		BandwidthLimiter.addLink();
	}
	
	@Override
	public void write(int b) throws IOException {
		BandwidthLimiter.limitNextBytes();
		this.os.write(b);
	}
	/** 
	 * 重构write(byte[], int, int)方法
	 * 将 b[] 切分数据包到最小数据包发送数据
	 * 引入BandwidthLimiter限速方法
	 * @see java.io.OutputStream#write(byte[], int, int)
	 */
	public void write(byte[] b, int off, int len) throws IOException {
		while(len >BUFF_SIZE){
			this.os.write(b, off, BUFF_SIZE);
			off += BUFF_SIZE;
			len -= BUFF_SIZE;
			BandwidthLimiter.limitNextBytes(BUFF_SIZE);
		}
		
		if(len >0){
			this.os.write(b, off, len);
			BandwidthLimiter.limitNextBytes(len);
		}
		
	}
	
	/** 
	 * 关闭IO流
	 * 重写父方法，引入BandwidthLimiter的IO计数器 关闭：减1
	 * @see java.io.OutputStream#close()
	 */
	public void close() throws IOException{
		BandwidthLimiter.removeLink();
		this.os.close();
	}
}