java.nio.channels.SocketChannel.read()方法的使用及代码示例

x33g5p2x  于2022-01-29 转载在 其他  
字(12.0k)|赞(0)|评价(0)|浏览(173)

本文整理了Java中java.nio.channels.SocketChannel.read()方法的一些代码示例,展示了SocketChannel.read()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。SocketChannel.read()方法的具体详情如下:
包路径:java.nio.channels.SocketChannel
类名称:SocketChannel
方法名:read

SocketChannel.read介绍

[英]Reads bytes from this socket channel and stores them in the specified array of buffers. This method attempts to read as many bytes as can be stored in the buffer array from this channel and returns the number of bytes actually read.

If a read operation is in progress, subsequent threads will block until the read is completed and will then contend for the ability to read.

Calling this method is equivalent to calling read(targets, 0,
[中]从这个套接字通道读取字节,并将它们存储在指定的缓冲区数组中。此方法尝试从该通道读取缓冲区数组中存储的尽可能多的字节,并返回实际读取的字节数。
如果读取操作正在进行,后续线程将阻塞,直到读取完成,然后争夺读取能力。
调用此方法相当于调用read(目标,0,

代码示例

代码示例来源:origin: iluwatar/java-design-patterns

/**
 * 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;
}

代码示例来源:origin: apache/avro

private void read(ByteBuffer buffer) throws IOException {
 buffer.clear();
 while (buffer.hasRemaining())
  if (channel.read(buffer) == -1)
   throw new EOFException();
 buffer.flip();
}

代码示例来源:origin: robovm/robovm

@Override
public int read() throws IOException {
  if (!channel.isBlocking()) {
    throw new IllegalBlockingModeException();
  }
  ByteBuffer buf = ByteBuffer.allocate(1);
  int result = channel.read(buf);
  return (result == -1) ? result : (buf.get(0) & 0xff);
}

代码示例来源:origin: wildfly/wildfly

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);
  }
}

代码示例来源:origin: apache/geode

@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;
}

代码示例来源:origin: kilim/kilim

ByteBuffer newbb = ByteBuffer.allocate(Math.max(buf.capacity() * 3 / 2, buf.position() + atleastN));
buf.rewind();
newbb.put(buf);
int n = ch.read(buf);

代码示例来源:origin: apache/geode

@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;
}

代码示例来源:origin: apache/avro

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);
 }
}

代码示例来源:origin: apache/nifi

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);

代码示例来源:origin: apache/incubator-gobblin

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();
  }
 }
}

代码示例来源:origin: apache/nifi

} finally {
  final ByteBuffer discardBuffer = ByteBuffer.allocate(8192);
  try {
    int bytesDiscarded = channel.read(discardBuffer);
    while (bytesDiscarded > 0) {
      discardBuffer.clear();
      bytesDiscarded = channel.read(discardBuffer);

代码示例来源:origin: apache/nifi

public void consume() throws IOException {
  channel.shutdownInput();
  final byte[] b = new byte[4096];
  final ByteBuffer buffer = ByteBuffer.wrap(b);
  int bytesRead;
  do {
    bytesRead = channel.read(buffer);
    buffer.flip();
  } while (bytesRead > 0);
}

代码示例来源:origin: apache/geode

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);

代码示例来源:origin: apache/nifi

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);

代码示例来源:origin: wildfly/wildfly

/**
 * 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();
  }
}

代码示例来源:origin: apache/geode

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);

代码示例来源:origin: EsotericSoftware/kryonet

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);

代码示例来源:origin: apache/nifi

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);

代码示例来源:origin: apache/nifi

public void consume() throws IOException {
  channel.shutdownInput();
  final byte[] b = new byte[4096];
  final ByteBuffer buffer = ByteBuffer.wrap(b);
  int readCount;
  do {
    readCount = channel.read(buffer);
    buffer.flip();
  } while (readCount > 0);
}

代码示例来源:origin: apache/geode

@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);
}

相关文章