Hm, hard to see. I'd feel a bit uncomfortable concerning input.mark()/reset() bc. they establishe states that easily might get shaken....
Maybe you could try to just plain read the socket to the end in a test environment, just to make sure wether the problem is on the sender or the receiver side?
Anyway, I provide a snippet of what I do. It different for I always read into my buffer succesivly until input is exhausted or the buffer it full. Than I evaluate it and separate the messages from it. If I reach the end of the buffer, I try to read further.
This does not require to mix ByteBuffer and Socket actions.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
| private final void evaluateMessage( SelectionKey key ) { NetLine line = (NetLine)key.attachment(); SocketChannel socketchannel = (SocketChannel)key.channel(); mBuffer.clear(); while( ! readAndParse( line, socketchannel ) ) ; }
private final boolean readAndParse( NetLine line, SocketChannel socketchannel ) { try { int nbytes = socketchannel.read( mBuffer ); if ( -1 == nbytes ) { Log.logger.fine( "Channel has EOF, closing line." ); line.close(); return true; } } catch ( Exception ex ) { .... exception handling ommited... return true; }
mBuffer.flip();
while ( mBuffer.position() < mBuffer.limit() ) { if ( mBuffer.remaining() < 2 ) { prepareBufferForNextRead(); return false; }
short ticketlen = mBuffer.getShort(); if ( ticketlen > mBuffer.remaining() ) { mBuffer.position( mBuffer.position() - 2 ); prepareBufferForNextRead(); return false; } ByteBuffer ticketbuffer = mBuffer.slice();
ticketbuffer.limit( (int)ticketlen ); mBuffer.position( mBuffer.position() + ticketlen ); BusTicket ticket = new BusTicket( ticketbuffer );
this.notifyIncomingBus( line, ticket ); } return true; } private final void prepareBufferForNextRead() { ByteBuffer rest = mBuffer.slice();
mBuffer.clear(); mBuffer.put( rest ); } |