java的NetStream

package com;

public class NetStream {

    private byte[] mData;
    private int mCapacity;

    private int rpos;
    private int wpos;
    private int wlimit;

    public NetStream(int capacity){
        mCapacity = capacity;
        mData = new byte[capacity];
    }

    public byte[] data(){
        return mData;
    }

    public int capacity(){
        return mCapacity;
    }

    public int canread(){
        return wpos - rpos;
    }

    public int getRpos(){
        return rpos;
    }
    public void setRpos(int rp){
        this.rpos = rp;
    }
    public int getWpos(){
        return wpos;
    }
    public void setWpos(int wp){
        this.wpos = wp;
    }

    public short getShort(){
        return (short) (((mData[rpos + 1] << 8) | mData[rpos + 0] & 0xff)); 
    }
    public int getInt(){
        return (int) ((((mData[rpos + 3] & 0xff) << 24)  
                | ((mData[rpos + 2] & 0xff) << 16)  
                | ((mData[rpos + 1] & 0xff) << 8) | ((mData[rpos + 0] & 0xff) << 0)));
    }

    public boolean getBytes(byte[] bytes){
        int leave = rpos;
        if (bytes.length >= leave){
            return false;
        }

        System.arraycopy(mData, rpos, bytes, 0, bytes.length);
        rpos += bytes.length;

        return true;
    }

    public void clearRead(){
        if (wpos == rpos){
            wpos = 0;
            rpos = 0;
            return;
        }
        int len = wpos - rpos;
        System.arraycopy(mData, rpos, mData, 0, len);
        rpos = 0;
        wpos = len;
    }

    public boolean put(short dt){
        if (wlimit - rpos < 2)
            return false;
        mData[wpos + 1] = (byte)(dt >> 8);
        mData[wpos + 0] = (byte)(dt >> 0);
        return true;
    }

    public boolean put(int dt){
        if (wlimit - rpos < 4)
            return false;
        mData[wpos + 3] = (byte) (dt >> 24);  
        mData[wpos + 2] = (byte) (dt >> 16);  
        mData[wpos + 1] = (byte) (dt >> 8);  
        mData[wpos + 0] = (byte) (dt >> 0);  
        return true;
    }

    public boolean put(byte[] bytes){
        int leave = wlimit - rpos;
        if (bytes.length >= leave){
            return false;
        }
        System.arraycopy(bytes, 0, mData, wpos, bytes.length);
        return true;
    }

    public boolean put(byte[] bytes, int offset, int len){
        int leave = wlimit - rpos;
        if (len >= leave){
            return false;
        }
        System.arraycopy(bytes, offset, mData, wpos, len);
        return true;
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值