client server - Java nio partial read -


my goal send different kind of messages client server, , text based. thing uncertain of how del partial reads here. have sure whole message , nothing more.

do have experience that?

here have far:

    private void handlenewclientmessage(selectionkey key) throws ioexception {     socketchannel sendingchannel = (socketchannel) key.channel();      bytebuffer receivingbuffer = bytebuffer.allocate(2048);     int bytesread = sendingchannel.read(receivingbuffer);     if (bytesread > 0) {         receivingbuffer.flip();          byte[] array = new byte[receivingbuffer.limit()];         receivingbuffer.get(array);         string message = new string(array);          system.out.println("server received "  +message);                }     selector.wakeup(); } 

but have no way of "ending" message , have 1 full message.

best regards, o

you can never sure won't read more 1 message unless read 1 byte @ time. (which don't suggest).

instead read as can bytebuffer , parse find end of message e.g. newline text.

when find end of line extract , convert string , process it. repeat until have partial message (or nothing left)

if find have part of message, compact() (if position() > 0) when have , try read() more.

this allows read many messages @ once can can handle incomplete messages.

note: need keep bytebuffer connection know partial messages have read before.

note: not work if have message larger buffer size. suggest using recycled direct bytebuffer of 1+ mb. direct bytebuffers pages of bytebuffer used allocated real memory.

if concerned performance re-use byte[] possible. need re-allocate if need more space have already.

btw, might find using bufferedreader plain io simpler use, still performance enough.


Popular posts from this blog

Php - Delimiter must not be alphanumeric or backslash -

Delphi interface implements -

java - How to create Table using Apache PDFBox -