Thanks all. I have revised my code. It's working now. Please comment.
and my question again:
Is my revised code clear enough to be a grizzly ProtocolParser tutorial that
grizzly official site can refer to?
http://www.nabble.com/file/p17209713/MyProtocolParser.java
MyProtocolParser.java
/*
* MyProtocolParser.java
*
* Created on 2008¦~05¤ë08¤é ¬P´Á¥|, ¤U¤È9:06
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package grizzlyserver;
import com.sun.grizzly.ProtocolParser;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
/**
*
* @author kentsang
*/
public class MyProtocolParser implements ProtocolParser<ByteBuffer> {
// saved buffer
private ByteBuffer savedBuffer = null;
// packet buffer
private ByteBuffer packetBuffer = null;
// temp byte array
private byte[] data = new byte[BUFFER_SIZE];
// size of temp byte array
private final static int BUFFER_SIZE = 8 * 1024;
public static final byte STX = 0x02;
public static final byte ETX = 0x03;
private boolean partial = true;
// array index of STX in data
private int start = -1;
// current position of savedBuffer
private int pos = 0;
// original limit of savedBuffer
private int limit = 0;
/**
* Creates a new instance of MyProtocolParser
*/
public MyProtocolParser() {
}
public void startBuffer(ByteBuffer bb) {
savedBuffer = bb;
savedBuffer.flip();
limit = savedBuffer.limit();
}
public boolean hasMoreBytesToParse() {
if (savedBuffer == null) return false;
boolean result = savedBuffer.position() < limit;
return result;
}
public boolean isExpectingMoreData() {
return partial;
}
public ByteBuffer getNextMessage() {
System.out.print("\r\nGetMessage:printByteBuffer: ");
printPacketBuffer();
System.out.println("\r\n");
return packetBuffer;
}
public boolean hasNextMessage() {
partial = false;
if (savedBuffer == null) return false;
while (savedBuffer.hasRemaining()) {
byte b = savedBuffer.get();
data[pos] = b;
if (b == STX) {
start = pos;
}
if (b == ETX && start > -1) {
int length = pos - start + 1;
byte[] newdata = new byte[length];
System.arraycopy(data, start, newdata, 0, length);
packetBuffer = ByteBuffer.wrap(newdata);
partial = false;
pos = 0;
start = -1;
break;
} else {
partial = true;
}
pos++;
}
return !partial;
}
public boolean releaseBuffer() {
if (!hasMoreBytesToParse()) {
if (savedBuffer != null) {
savedBuffer.clear();
}
savedBuffer = null;
} else {
// I dunno this else block. In my case, it seems that
hasMoreBytesToParse() never return false in releaseBuffer()
savedBuffer.flip();
}
return partial;
}
}
--
View this message in context: http://www.nabble.com/ProtocolParser-implementation-II-tp17152654p17209713.html
Sent from the Grizzly - Users mailing list archive at Nabble.com.