0

I’m working on java.nio no-blocking client server application, the application has a very easy custom protocol as:

MyApplcationProtocol:
int lenpalcket;
int filedone;
String Description
byte[] myBodyProtcol

(the body length is not fixed.)

The problem is that sometime I don’t have enough byte inside ByteBuffer and then the decode fail

while (myByteBuffer.hasRemaining()) {
   Utils.fillMyClass(myclass,myByteBuffer);

public void fillMyClass(myclass,myByteBuffer){
   myclass.filedone = myByteBuffer.getInt();
   ...
   int bodyLen = myByteBuffer.getInt();
   byte[] bodyByte = new byte[bodyLen];
   myByteBuffer.get(bodyByte);
   ...
}

I have to wait the next buffer to complete fill the class, so I want to avoid to put a sleep because it blocks the thread. Is there a pattern/way/link/example to solve this problem?

I tried also to store the “unread bytes” in a temp buffer, but I don’t like it, and sometimes i doesn’t work correctly.

Thank you, any help is appreciated

J.R.
  • 2,335
  • 2
  • 19
  • 21
  • `the body length is not fixed.` Can you think about the largest possible packet? I read somewhere a while ago that you should always create a buffer as big as the largest possible packet. It's not fixed/needs to be split to avoid empty bytes but you would always be sure to have enough space for your largest possible packet – Loki Mar 26 '15 at 15:02
  • You need context and state in the socket class. This is inherent when handling protocols on top of TCP in non-blocking designs. TBH, byte-by-byte state-machines for protocols are not a bad idea in thread-per connections servers either. – Martin James Mar 26 '15 at 19:15

0 Answers0