/** * Reads and returns {@link ByteBuffer} from the underlying {@link SocketChannel} represented by * the <code>key</code>. Due to the fact that there is a dedicated channel for each client * connection we don't need to store the sender. */ @Override public ByteBuffer read(SelectionKey key) throws IOException { SocketChannel socketChannel = (SocketChannel) key.channel(); ByteBuffer buffer = ByteBuffer.allocate(1024); int read = socketChannel.read(buffer); buffer.flip(); if (read == -1) { throw new IOException("Socket closed"); } return buffer; }
public void run() { ByteBuffer buf=direct_buffers? ByteBuffer.allocateDirect(RoundTrip.PAYLOAD) : ByteBuffer.allocate(RoundTrip.PAYLOAD); for(;;) { try { buf.position(0); int num=client_channel.read(buf); if(num == -1) break; if(num != RoundTrip.PAYLOAD) throw new IllegalStateException("expected " + RoundTrip.PAYLOAD + " bytes, but got only " + num); if(receiver != null) { buf.flip(); int offset=buf.hasArray()? buf.arrayOffset() + buf.position() : buf.position(), len=buf.remaining(); if(!buf.isDirect()) receiver.receive(null, buf.array(), offset, len); else { // by default use a copy; but of course implementers of Receiver can override this byte[] tmp=new byte[len]; buf.get(tmp, 0, len); receiver.receive(null, tmp, 0, len); } } } catch(Exception e) { e.printStackTrace(); } } Util.close(client_channel); } }
@Override public ByteBuffer readAtLeast(SocketChannel channel, int bytes, ByteBuffer wrappedBuffer, DMStats stats) throws IOException { if (peerAppData.capacity() > bytes) { // we already have a buffer that's big enough if (peerAppData.capacity() - peerAppData.position() < bytes) { peerAppData.compact(); peerAppData.flip(); } } else { peerAppData = Buffers.expandReadBufferIfNeeded(TRACKED_RECEIVER, peerAppData, bytes, this.stats); } while (peerAppData.remaining() < bytes) { wrappedBuffer.limit(wrappedBuffer.capacity()); int amountRead = channel.read(wrappedBuffer); if (amountRead < 0) { throw new EOFException(); } if (amountRead > 0) { wrappedBuffer.flip(); // prep the decoded buffer for writing peerAppData.compact(); peerAppData = unwrap(wrappedBuffer); // done writing to the decoded buffer - prep it for reading again peerAppData.flip(); } } return peerAppData; }
@Override public ByteBuffer readAtLeast(SocketChannel channel, int bytes, ByteBuffer wrappedBuffer, DMStats stats) throws IOException { ByteBuffer buffer = wrappedBuffer; Assert.assertTrue(buffer.capacity() - lastProcessedPosition >= bytes); // read into the buffer starting at the end of valid data buffer.limit(buffer.capacity()); buffer.position(lastReadPosition); while (buffer.position() < (lastProcessedPosition + bytes)) { int amountRead = channel.read(buffer); if (amountRead < 0) { throw new EOFException(); } } // keep track of how much of the buffer contains valid data with lastReadPosition lastReadPosition = buffer.position(); // set up the buffer for reading and keep track of how much has been consumed with // lastProcessedPosition buffer.limit(lastProcessedPosition + bytes); buffer.position(lastProcessedPosition); lastProcessedPosition += bytes; return buffer; }
public synchronized List<ByteBuffer> readBuffers() throws IOException { List<ByteBuffer> buffers = new ArrayList<>(); while (true) { header.clear(); while (header.hasRemaining()) { if (channel.read(header) < 0) throw new ClosedChannelException(); } header.flip(); int length = header.getInt(); if (length == 0) { // end of buffers return buffers; } ByteBuffer buffer = ByteBuffer.allocate(length); while (buffer.hasRemaining()) { if (channel.read(buffer) < 0) throw new ClosedChannelException(); } buffer.flip(); buffers.add(buffer); } }
final ByteBuffer emptyMessage = ByteBuffer.allocate(0); ByteBuffer unwrapBuffer = ByteBuffer.allocate(0); if (unwrapBuffer.capacity() - unwrapBuffer.position() < 1) { logger.trace("Enlarging size of Buffer for NEED_UNWRAP portion of Handshake"); final ByteBuffer tempBuffer = ByteBuffer.allocate(unwrapBuffer.capacity() + sslEngine.getSession().getApplicationBufferSize()); tempBuffer.put(unwrapBuffer); unwrapBuffer = tempBuffer; unwrapBuffer.flip(); continue; final int bytesRead = socketChannel.read(unwrapBuffer); unwrapBuffer.flip(); logger.debug("Read {} bytes for NEED_UNWRAP portion of Handshake", bytesRead);
private void read() throws IOException { int lastBytes = 0; while ((lastBytes = this.proxy.read(this.buffer)) > 0) { // totalBytesRead has to be stateful because read() might return at arbitrary points this.totalBytesRead += lastBytes; } if (this.totalBytesRead >= OK_REPLY.limit()) { byte[] temp = this.buffer.array(); this.buffer.flip(); if (OK_REPLIES.contains(ByteBuffer.wrap(temp, 0, OK_REPLY.limit()))) { // drain the rest of the HTTP response. 2 consecutive CRLFs signify the end of an HTTP // message (some proxies return newlines instead of CRLFs) for (int i = OK_REPLY.limit(); i <= (this.buffer.limit() - 4); i++) { if (((temp[i] == '\n') && (temp[i + 1] == '\n')) || ((temp[i + 1] == '\n') && (temp[i + 2] == '\n')) || ((temp[i + 2] == '\n') && (temp[i + 3] == '\n')) || ((temp[i] == '\r') && (temp[i + 1] == '\n') && (temp[i + 2] == '\r') && (temp[i + 3] == '\n'))) { this.state = null; this.buffer.position(i + 4); new ReadWriteHandler(this.proxy, this.buffer, this.client, this.selector); return; } } } else { LOG.error("Got non-200 response from proxy: [" + new String(temp, 0, OK_REPLY.limit(), ConfigurationKeys.DEFAULT_CHARSET_ENCODING) + "], closing connection."); closeChannels(); } } }
final int individualRead = 60; final int preexistingBytes = 10; ByteBuffer wrappedBuffer = ByteBuffer.allocate(1000); SocketChannel mockChannel = mock(SocketChannel.class); when(mockChannel.read(any(ByteBuffer.class))).thenAnswer(new Answer<Integer>() { @Override public Integer answer(InvocationOnMock invocation) throws Throwable { verify(mockChannel, times(3)).read(isA(ByteBuffer.class)); assertThat(data.position()).isEqualTo(0); assertThat(data.limit()).isEqualTo(amountToRead); assertThat(nioEngine.lastReadPosition).isEqualTo(individualRead * 3 + preexistingBytes); verify(mockChannel, times(5)).read(any(ByteBuffer.class)); assertThat(data.position()).isEqualTo(amountToRead);
while (!finished && (count = socketChannel.read(AbstractSocketHandler.this.readingBuffer)) > 0){ byte lastByte = AbstractSocketHandler.this.readingBuffer.get(AbstractSocketHandler.this.readingBuffer.position() - 1); if (AbstractSocketHandler.this.readingBuffer.remaining() == 0 || lastByte == AbstractSocketHandler.this.endOfMessageByte) { this.processBuffer(selectionKey); if (AbstractSocketHandler.this.readingBuffer.position() > 0) {// flush remainder, since nothing else is coming this.processBuffer(selectionKey);
/** * Reads length and then length bytes into the data buffer, which is grown if needed. * @param ch The channel to read data from * @return The data buffer (position is 0 and limit is length), or null if not all data could be read. */ public ByteBuffer readLengthAndData(SocketChannel ch) throws Exception { if(bufs[0].hasRemaining() && ch.read(bufs[0]) < 0) throw new EOFException(); if(bufs[0].hasRemaining()) return null; int len=bufs[0].getInt(0); if(bufs[1] == null || len > bufs[1].capacity()) bufs[1]=ByteBuffer.allocate(len); bufs[1].limit(len); if(bufs[1].hasRemaining() && ch.read(bufs[1]) < 0) throw new EOFException(); if(bufs[1].hasRemaining()) return null; try { return (ByteBuffer)bufs[1].duplicate().flip(); } finally { bufs[0].clear(); bufs[1].clear(); } }
buffer.limit(buffer.position()); buffer.position(0); int bytesRead = channel.read(buffer); if (bytesRead == -1) { throw new IOException("EOF"); buffer.flip(); if ((HEADER_LENGTH + bodyLength) > requestLength) { buffer.position(buffer.position() - 2 /* since we read two bytes */); buffer.compact(); oldBuffer.position(0); buffer = ByteBuffer.allocate(HEADER_LENGTH + bodyLength); buffer.put(oldBuffer);
if (readBuffer.remaining() < lengthLength) { readBuffer.compact(); int bytesRead = socketChannel.read(readBuffer); readBuffer.flip(); if (bytesRead == -1) throw new SocketException("Connection is closed."); lastReadTime = System.currentTimeMillis(); int bytesRead = socketChannel.read(readBuffer); readBuffer.flip(); if (bytesRead == -1) throw new SocketException("Connection is closed."); lastReadTime = System.currentTimeMillis(); int startPosition = readBuffer.position(); int oldLimit = readBuffer.limit(); readBuffer.limit(startPosition + length); if (readBuffer.position() - startPosition != length) throw new KryoNetException("Incorrect number of bytes (" + (startPosition + length - readBuffer.position()) + " remaining) used to deserialize object: " + object);
int readCount = 0; try { readCount = channel.read(writableInBuffer); } catch (IOException e) { logger.error("{} Failed to readData due to {}", new Object[]{this, e}); if (unwrapResponse.getStatus().equals(Status.CLOSED)) { final ByteBuffer discardBuffer = ByteBuffer.allocate(8192); int bytesDiscarded = channel.read(discardBuffer); while (bytesDiscarded > 0) { discardBuffer.clear(); bytesDiscarded = channel.read(discardBuffer);
@Test public void readAtLeast() throws Exception { final int amountToRead = 150; final int individualRead = 60; final int preexistingBytes = 10; ByteBuffer wrappedBuffer = ByteBuffer.allocate(1000); SocketChannel mockChannel = mock(SocketChannel.class); // force a compaction by making the decoded buffer appear near to being full ByteBuffer unwrappedBuffer = nioSslEngine.peerAppData; unwrappedBuffer.position(unwrappedBuffer.capacity() - individualRead); unwrappedBuffer.limit(unwrappedBuffer.position() + preexistingBytes); // simulate some socket reads when(mockChannel.read(any(ByteBuffer.class))).thenAnswer(new Answer<Integer>() { @Override public Integer answer(InvocationOnMock invocation) throws Throwable { ByteBuffer buffer = invocation.getArgument(0); buffer.position(buffer.position() + individualRead); return individualRead; } }); TestSSLEngine testSSLEngine = new TestSSLEngine(); testSSLEngine.addReturnResult(new SSLEngineResult(OK, NEED_UNWRAP, 0, 0)); nioSslEngine.engine = testSSLEngine; ByteBuffer data = nioSslEngine.readAtLeast(mockChannel, amountToRead, wrappedBuffer, mockStats); verify(mockChannel, times(3)).read(isA(ByteBuffer.class)); assertThat(data.position()).isEqualTo(0); assertThat(data.limit()).isEqualTo(individualRead * 3 + preexistingBytes); }