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;
}
}
java的NetStream
最新推荐文章于 2024-04-15 15:10:32 发布