private final class WebSocketProtocolHandler implements IConnectHandler, IDataHandler, IDisconnectHandler {
// network data
private ByteBuffer rawBuffer = null;
public boolean onConnect(INonBlockingConnection connection) throws IOException, BufferUnderflowException, MaxReadSizeExceededException {
........
return true;
}
public boolean onData(INonBlockingConnection connection) throws IOException, BufferUnderflowException, ClosedChannelException, MaxReadSizeExceededException {
if (connection.isOpen()) {
// copying available network data into raw data buffer
int available = connection.available();
ByteBuffer[] data = null;
if (available > 0) {
data = connection.readByteBufferByLength(available);
}
onData(data);
}
return true;
}
void onData(ByteBuffer[] data) throws IOException {
if (data == null) {
if (rawBuffer == null) {
rawBuffer = ByteBuffer.allocate(0);
}
} else {
if (rawBuffer == null) {
rawBuffer = HttpUtils.merge(data);
} else {
rawBuffer = HttpUtils.merge(rawBuffer, data);
}
}
parse(rawBuffer);
if (!rawBuffer.hasRemaining()) {
rawBuffer = null;
}
}
void parse(ByteBuffer buffer) throws IOException {
while (buffer.hasRemaining()) {
WebSocketMessage msg = WebSocketMessage.parse(buffer);
if (msg == null) {
return;
} else {
if (msg.isTextMessage()) {
synchronized (inQueue) {
inQueueVersion++;
inQueue.add(msg);
inQueue.notifyAll();
}
synchronized (webSocketHandlerGuard) {
if (webSocketHandlerAdapter != null) {
webSocketHandlerAdapter.onMessage(WebSocketConnection.this);
}
}
} else if (msg.isCloseMessage()) {
if (isCloseMsgSent.get()) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + getId() + "] echo close msg reveived. Destroying connection");
}
writeMessageIgnoreClose(msg);
destroy();
// peer initiated close
} else {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + getId() + "] close msg reveived. echoing it and destroying connection");
}
isCloseMsgSent.set(true);
writeMessageIgnoreClose(msg);
destroy();
}
} else {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("[" + getId() + "] binary message received. The ws draft does not longer allow binary messages. Ignoring it");
}
}
}
}
}
在這裡把數據從 onData 中收取下了並且進行轉換後存入到 inQueue 中。這裡已經知道它是怎麼收取數據了,就差最後一步,怎麼轉化數據,分離有效信息的。看到這幾行代碼,回想下自己原來寫的也可以這麼做就行了。(
)if (connection.isOpen()) {
// copying available network data into raw data buffer
int available = connection.available(); //這裡還沒有仔細查看,如果誰有時間查看了,希望也轉告我原理
ByteBuffer[] data = null;
if (available > 0) {
data = connection.readByteBufferByLength(available);
}
onData(data);
}