Well I am working on a multiplayer game type thing and this is a class I made for sending bytes to clients. All the methods and what not are documented, but the class isn't completely finished. All that is really left is looping through the bytes array sending what is needed (easy, but I haven't bothered to put it in).
import java.util.Arrays;
/**
* User: Matthew
* Date: Jun 8, 2009
* Time: 12:49:04 AM
*
* Handles bytes that need to be written to the clients.
*/
public class Buffer {
/**
* This is our array of bytes in the buffer.
*/
public byte[] array;
/**
* The position of where in the array to place the byte
*/
public int position;
/**
* How many bytes are in the buffer.
*/
public int length;
/**
* If the reset method is called, the buffer will only be reset to here. Everything after it will stay the same.
*/
public int mark;
/**
* The initial capacity of our buffer. Basically how many bytes it can hold at once.
*/
public final int initialCapacity;
/**
* Creates a new buffer with 100 available spots.
*/
public Buffer() {
this(100);
}
/**
* Creats a new buffer with * amount of slots.
* @param length the amount of available slots we want.
*/
public Buffer(int length) {
this(new byte[length]);
}
/**
* Creates a new buffer from an existing array of bytes.
* @param array The array of bytes we want to start with.
*/
public Buffer(byte[] array) {
this.array = array;
this.length = 0;
this.mark = array.length;
this.initialCapacity = array.length;
}
/**
* Sets how many bytes we want to reset.
* @param mark the amount of bytes.
*/
public void setMark(int mark) {
this.mark = mark;
}
/**
* Resets everything before our mark.
*/
public void reset() {
for(int i = 0; i > mark; i++) {
array[i] = -1;
}
position = 0;
}
/**
* Tells us how many remaining slots we have.
* @return the remaining slots we have.
*/
public int getRemainingSlots() {
return (initialCapacity - length);
}
/**
* Adds a byte to the buffer.
* @param b the byte to add to the buffer.
*/
public void addByte(byte b) {
try {
if(position == (initialCapacity + 1)) {
throw new Exception("Buffer full.");
} else {
array[position] = b;
position++;
}
} catch(Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
/**
* Resets the position back to 0
*/
public void resetPosition() {
position = 0;
}
/**
* Removes everyting from the array.
*/
public void empty() {
Arrays.fill(array,(byte)0);
}
}
Have fun.