简体   繁体   中英

Erroneous reading on Non-blocking java socket client

I have a client/server application written in Java using non-blocking IO.
There are several message types which are transferred as Json encoding and a message delimiter appended at the end of each message.
The client reads bytes and merges the messages which are coming in chunks. On regular cases it is working but in heavy load cases i get a chunk which includes messages which are not in right order. I mean, lets say I have a message m1="AAABBBCCCDDD" and m2="EEEFFF" and delimiter is "||". When the message is received it is supposed to be "AAABBBCCCDDD||EEEFFF||". But it is received "AAABBBEEEFFF||CCCDDD||". As a result it fails to parse the message.
Actually, I would like to hear the ideas that should be considered while developing network applications using non-blocking IO. what can be the reason of being in the wrong order..? Reader code is like this:

ByteBuffer buffer = ByteBuffer.allocate(20000);
count = 0;
while ((count = channel.read(buffer)) > 0) {
    buffer.flip();
    processSocketData(Charset.defaultCharset().decode(buffer));
}

processSocketData() method is like that:

socketData.append(newData);
delIndex = socketData.indexOf(cGlobals.delimiterSequence);

if (delIndex > -1) {
    processRawMessage(socketData.substring(0, delIndex));
    socketData.delete(0, delIndex + cGlobals.delimiterSize);
}

在处理之前,您需要先进行flip()在处理完缓冲区之后,还需要compact()clear()缓冲区。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM