| 179 | protected static final int HEADER_FLAG_FOLLOWING = 0x10000; |
| 180 | |
| 181 | public byte[] read(SocketChannel ch) throws IOException { |
| 182 | if (_readHeader) { // Start of a packet |
| 183 | if (_readBuffer.position() == 0) { |
| 184 | _readBuffer.limit(4); |
| 185 | } |
| 186 | |
| 187 | if (ch.read(_readBuffer) == -1) { |
| 188 | throw new IOException("Connection closed with -1 on reading size."); |
| 189 | } |
| 190 | |
| 191 | if (_readBuffer.hasRemaining()) { |
| 192 | LOGGER.trace("Need to read the rest of the packet length"); |
| 193 | return null; |
| 194 | } |
| 195 | _readBuffer.flip(); |
| 196 | int header = _readBuffer.getInt(); |
| 197 | int readSize = (short)header; |
| 198 | if (LOGGER.isTraceEnabled()) { |
| 199 | LOGGER.trace("Packet length is " + readSize); |
| 200 | } |
| 201 | |
| 202 | if (readSize > MAX_SIZE_PER_PACKET) { |
| 203 | throw new IOException("Wrong packet size: " + readSize); |
| 204 | } |
| 205 | |
| 206 | if (!_gotFollowingPacket) { |
| 207 | _plaintextBuffer = ByteBuffer.allocate(2000); |
| 208 | } |
| 209 | |
| 210 | if ((header & HEADER_FLAG_FOLLOWING) != 0) { |
| 211 | _gotFollowingPacket = true; |
| 212 | } else { |
| 213 | _gotFollowingPacket = false; |
| 214 | } |
| 215 | |
| 216 | _readBuffer.clear(); |
| 217 | _readHeader = false; |
| 218 | |
| 219 | if (_readBuffer.capacity() < readSize) { |
| 220 | if (LOGGER.isTraceEnabled()) { |
| 221 | LOGGER.trace("Resizing the byte buffer from " + _readBuffer.capacity()); |
| 222 | } |
| 223 | _readBuffer = ByteBuffer.allocate(readSize); |
| 224 | } |
| 225 | _readBuffer.limit(readSize); |
| 226 | } |
| 227 | |
| 228 | if (ch.read(_readBuffer) == -1) { |
| 229 | throw new IOException("Connection closed with -1 on read."); |
| 230 | } |
| 231 | |
| 232 | if (_readBuffer.hasRemaining()) { // We're not done yet. |
| 233 | if (LOGGER.isTraceEnabled()) { |
| 234 | LOGGER.trace("Still has " + _readBuffer.remaining()); |
| 235 | } |
| 236 | return null; |
| 237 | } |
| 238 | |