Java 类java.nio.channels.ByteChannel 实例源码

项目:elasticsearch_my    文件:FileSystemUtilsTests.java   
@Before
public void copySourceFilesToTarget() throws IOException, URISyntaxException {
    src = createTempDir();
    dst = createTempDir();
    Files.createDirectories(src);
    Files.createDirectories(dst);
    txtFile = src.resolve("text-file.txt");

    try (ByteChannel byteChannel = Files.newByteChannel(txtFile, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE)) {
        expectedBytes = new byte[3];
        expectedBytes[0] = randomByte();
        expectedBytes[1] = randomByte();
        expectedBytes[2] = randomByte();
        byteChannel.write(ByteBuffer.wrap(expectedBytes));
    }
}
项目:NIOHttp    文件:FutureDemo.java   
private void writeGetRequestTo(ByteChannel channel) throws IOException {

    // @formatter:off
    String request = new StringBuilder("GET").append(SPACE)
        .append(this.url.getPath()).append(SPACE).append("HTTP/1.1")
                .append(CRLF)
        .append("User-Agent: NIOHttp/0.1 Java")
                .append(CRLF)
                .append("Host:").append(SPACE).append(url.getHost())
                .append(CRLF)
                .append("Accept-Language: en-us").append(CRLF)
                .append("Connection: close").append(CRLF).append(CRLF)
                .toString();
           // @formatter:on

    ByteBuffer sending = ByteBuffer.allocate(request.getBytes().length);
    sending.put(request.getBytes());
    sending.flip();
    channel.write(sending);
    }
项目:NIOHttp    文件:StreamDemo.java   
private void writeGetRequestTo(ByteChannel channel) throws IOException {

    // @formatter:off
    String request = new StringBuilder("GET").append(SPACE)
        .append(this.url.getPath()).append(SPACE).append("HTTP/1.1")
                .append(CRLF)
        .append("User-Agent: NIOHttp/0.1 Java")
                .append(CRLF)
                .append("Host:").append(SPACE).append(url.getHost())
                .append(CRLF)
                .append("Accept-Language: en-us").append(CRLF)
                .append("Connection: close").append(CRLF).append(CRLF)
                .toString();
           // @formatter:on

    ByteBuffer sending = ByteBuffer.allocate(request.getBytes().length);
    sending.put(request.getBytes());
    sending.flip();
    channel.write(sending);
    }
项目:libcommon    文件:ChannelHelper.java   
/**
 * ByteChannelからchar配列を読み込む
 * @param channel
 * @return
 * @throws IOException
 */
public static char[] readCharArray(@NonNull final ByteChannel channel)
    throws IOException {

    final int n = readInt(channel);
    final ByteBuffer buf = ByteBuffer.allocate(n * 2).order(ByteOrder.BIG_ENDIAN);
    final int readBytes = channel.read(buf);
    if (readBytes != n * 2) throw new IOException();
    buf.clear();
    final CharBuffer result = buf.asCharBuffer();
    if (result.hasArray()) {
        return result.array();
    }  else {
        final char[] b = new char[n];
        result.get(b);
        return b;
    }
}
项目:libcommon    文件:ChannelHelper.java   
/**
 * ByteChannelからshort配列を読み込む
 * @param channel
 * @return
 * @throws IOException
 */
public static short[] readShortArray(@NonNull final ByteChannel channel)
    throws IOException {

    final int n = readInt(channel);
    final ByteBuffer buf = ByteBuffer.allocate(n * 2).order(ByteOrder.BIG_ENDIAN);
    final int readBytes = channel.read(buf);
    if (readBytes != n * 2) throw new IOException();
    buf.clear();
    final ShortBuffer result = buf.asShortBuffer();
    if (result.hasArray()) {
        return result.array();
    }  else {
        final short[] b = new short[n];
        result.get(b);
        return b;
    }
}
项目:libcommon    文件:ChannelHelper.java   
/**
 * ByteChannelからint配列を読み込む
 * @param channel
 * @return
 * @throws IOException
 */
public static int[] readIntArray(@NonNull final ByteChannel channel)
    throws IOException {

    final int n = readInt(channel);
    final ByteBuffer buf = ByteBuffer.allocate(n * 4).order(ByteOrder.BIG_ENDIAN);
    final int readBytes = channel.read(buf);
    if (readBytes != n * 4) throw new IOException();
    buf.clear();
    final IntBuffer result = buf.asIntBuffer();
    if (result.hasArray()) {
        return result.array();
    }  else {
        final int[] b = new int[n];
        result.get(b);
        return b;
    }
}
项目:libcommon    文件:ChannelHelper.java   
/**
 * ByteChannelからlong配列を読み込む
 * @param channel
 * @return
 * @throws IOException
 */
public static long[] readLongArray(@NonNull final ByteChannel channel)
    throws IOException {

    final int n = readInt(channel);
    final ByteBuffer buf = ByteBuffer.allocate(n * 8).order(ByteOrder.BIG_ENDIAN);
    final int readBytes = channel.read(buf);
    if (readBytes != n * 8) throw new IOException();
    buf.clear();
    final LongBuffer result = buf.asLongBuffer();
    if (result.hasArray()) {
        return result.array();
    }  else {
        final long[] b = new long[n];
        result.get(b);
        return b;
    }
}
项目:libcommon    文件:ChannelHelper.java   
/**
 * ByteChannelからfloat配列を読み込む
 * @param channel
 * @return
 * @throws IOException
 */
public static float[] readFloatArray(@NonNull final ByteChannel channel)
    throws IOException {

    final int n = readInt(channel);
    final ByteBuffer buf = ByteBuffer.allocate(n * 4).order(ByteOrder.BIG_ENDIAN);
    final int readBytes = channel.read(buf);
    if (readBytes != n * 4) throw new IOException();
    buf.clear();
    final FloatBuffer result = buf.asFloatBuffer();
    if (result.hasArray()) {
        return result.array();
    }  else {
        final float[] b = new float[n];
        result.get(b);
        return b;
    }
}
项目:libcommon    文件:ChannelHelper.java   
/**
 * ByteChannelからdouble配列を読み込む
 * @param channel
 * @return
 * @throws IOException
 */
public static double[] readDoubleArray(@NonNull final ByteChannel channel)
    throws IOException {

    final int n = readInt(channel);
    final ByteBuffer buf = ByteBuffer.allocate(n * 8).order(ByteOrder.BIG_ENDIAN);
    final int readBytes = channel.read(buf);
    if (readBytes != n * 8) throw new IOException();
    buf.clear();
    final DoubleBuffer result = buf.asDoubleBuffer();
    if (result.hasArray()) {
        return result.array();
    }  else {
        final double[] b = new double[n];
        result.get(b);
        return b;
    }
}
项目:nnio    文件:FilesTest.java   
@Test
public void newByteChannel() throws IOException {
  Path test = base.resolve("test");
  BufferedWriter bw = Files.newBufferedWriter(test, Charset.forName("UTF-8"));
  bw.write(text);
  bw.close();
  ByteChannel bc = Files.newByteChannel(test);
  ByteBuffer bb = ByteBuffer.allocate(data.length + 1);
  int read = bc.read(bb);
  assertEquals(data.length, read);
  assertEquals(data.length, bb.position());
  bb.flip();
  byte[] buffer = new byte[data.length];
  bb.get(buffer, 0, data.length);
  assertArrayEquals(data, buffer);
}
项目:spring-boot-concourse    文件:HttpTunnelServerTests.java   
@Before
public void setup() throws Exception {
    MockitoAnnotations.initMocks(this);
    this.server = new HttpTunnelServer(this.serverConnection);
    given(this.serverConnection.open(anyInt())).willAnswer(new Answer<ByteChannel>() {
        @Override
        public ByteChannel answer(InvocationOnMock invocation) throws Throwable {
            MockServerChannel channel = HttpTunnelServerTests.this.serverChannel;
            channel.setTimeout((Integer) invocation.getArguments()[0]);
            return channel;
        }
    });
    this.servletRequest = new MockHttpServletRequest();
    this.servletRequest.setAsyncSupported(true);
    this.servletResponse = new MockHttpServletResponse();
    this.request = new ServletServerHttpRequest(this.servletRequest);
    this.response = new ServletServerHttpResponse(this.servletResponse);
    this.serverChannel = new MockServerChannel();
}
项目:bt    文件:GetTorrent.java   
void handleCompletion(FetchTask task, Throwable ex) {
    if(ex != null)
        return;
    if(task.getState() != FetchState.SUCCESS) {
        printErr("download "+task.infohash().toString(false)+" failed\n");
        return;
    }

    task.getResult().ifPresent(buf -> {
        Path torrentName = currentWorkDir.resolve(task.infohash().toString(false) +".torrent");
        try(ByteChannel chan = Files.newByteChannel(torrentName, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {
            ByteBuffer torrent = TorrentUtils.wrapBareInfoDictionary(buf);

            Optional<String> name = TorrentUtils.getTorrentName(torrent);

            chan.write(torrent);
            name.ifPresent(str -> {
                println("torrent name: "+ str);
            });
            println("written meta to "+torrentName);
        } catch (IOException e) {
            handleException(e);
        }
    });
}
项目:bt    文件:PeerConnectionFactory.java   
private ChannelPipeline createPipeline(
        Peer peer,
        ByteChannel channel,
        BorrowedBuffer<ByteBuffer> in,
        BorrowedBuffer<ByteBuffer> out,
        Optional<MSECipher> cipherOptional) {

    ChannelPipelineBuilder builder = channelPipelineFactory.buildPipeline(peer);
    builder.channel(channel);
    builder.protocol(protocol);
    builder.inboundBuffer(in);
    builder.outboundBuffer(out);

    cipherOptional.ifPresent(cipher -> {
        builder.decoders(new CipherBufferMutator(cipher.getDecryptionCipher()));
        builder.encoders(new CipherBufferMutator(cipher.getEncryptionCipher()));
    });

    return builder.build();
}
项目:PhoneChat    文件:WebSocketClient.java   
public boolean cancel(boolean mayInterruptIfRunning)
{
    try
    {
        ByteChannel channel=null;
        synchronized (this)
        {
            if (_connection==null && _exception==null && _channel!=null)
            {
                channel=_channel;
                _channel=null;
            }
        }

        if (channel!=null)
        {
            closeChannel(channel,WebSocketConnectionRFC6455.CLOSE_NO_CLOSE,"cancelled");
            return true;
        }
        return false;
    }
    finally
    {
        _done.countDown();
    }
}
项目:PhoneChat    文件:ChannelEndPoint.java   
protected ChannelEndPoint(ByteChannel channel, int maxIdleTime) throws IOException
{
    this._channel = channel;
    _maxIdleTime=maxIdleTime;
    _socket=(channel instanceof SocketChannel)?((SocketChannel)channel).socket():null;
    if (_socket!=null)
    {
        _local=(InetSocketAddress)_socket.getLocalSocketAddress();
        _remote=(InetSocketAddress)_socket.getRemoteSocketAddress();
        _socket.setSoTimeout(_maxIdleTime);
    }
    else
    {
        _local=_remote=null;
    }
}
项目:spring-boot-concourse    文件:SocketTargetServerConnectionTests.java   
@Test
public void timeout() throws Exception {
    this.server.delay(1000);
    this.server.start();
    ByteChannel channel = this.connection.open(10);
    long startTime = System.currentTimeMillis();
    try {
        channel.read(ByteBuffer.allocate(5));
        fail("No socket timeout thrown");
    }
    catch (SocketTimeoutException ex) {
        // Expected
        long runTime = System.currentTimeMillis() - startTime;
        assertThat(runTime).isGreaterThanOrEqualTo(10L);
        assertThat(runTime).isLessThan(10000L);
    }
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:HttpTunnelServerTests.java   
@Before
public void setup() throws Exception {
    MockitoAnnotations.initMocks(this);
    this.server = new HttpTunnelServer(this.serverConnection);
    given(this.serverConnection.open(anyInt())).willAnswer(new Answer<ByteChannel>() {
        @Override
        public ByteChannel answer(InvocationOnMock invocation) throws Throwable {
            MockServerChannel channel = HttpTunnelServerTests.this.serverChannel;
            channel.setTimeout((Integer) invocation.getArguments()[0]);
            return channel;
        }
    });
    this.servletRequest = new MockHttpServletRequest();
    this.servletRequest.setAsyncSupported(true);
    this.servletResponse = new MockHttpServletResponse();
    this.request = new ServletServerHttpRequest(this.servletRequest);
    this.response = new ServletServerHttpResponse(this.servletResponse);
    this.serverChannel = new MockServerChannel();
}
项目:neoscada    文件:NioProcessor.java   
@Override
protected void destroy(NioSession session) throws Exception {
    ByteChannel ch = session.getChannel();
    SelectionKey key = session.getSelectionKey();
    if (key != null) {
        key.cancel();
    }
    ch.close();
}
项目:Responder-Android    文件:SocketChannelIOHelper.java   
/** Returns whether the whole outQueue has been flushed */
public static boolean batch( WebSocketImpl ws, ByteChannel sockchannel ) throws IOException {
    ByteBuffer buffer = ws.outQueue.peek();
    WrappedByteChannel c = null;

    if( buffer == null ) {
        if( sockchannel instanceof WrappedByteChannel ) {
            c = (WrappedByteChannel) sockchannel;
            if( c.isNeedWrite() ) {
                c.writeMore();
            }
        }
    } else {
        do {// FIXME writing as much as possible is unfair!!
            /*int written = */sockchannel.write( buffer );
            if( buffer.remaining() > 0 ) {
                return false;
            } else {
                ws.outQueue.poll(); // Buffer finished. Remove it.
                buffer = ws.outQueue.peek();
            }
        } while ( buffer != null );
    }

    if( ws.outQueue.isEmpty() && ws.isFlushAndClose() && ws.getDraft().getRole() == Role.SERVER ) {//
        synchronized ( ws ) {
            ws.closeConnection();
        }
    }
    return c != null ? !( (WrappedByteChannel) sockchannel ).isNeedWrite() : true;
}
项目:Responder-Android    文件:AbstractClientProxyChannel.java   
/**
 * @param towrap
 *            The channel to the proxy server
 **/
public AbstractClientProxyChannel( ByteChannel towrap ) {
    super( towrap );
    try {
        proxyHandshake = ByteBuffer.wrap( buildHandShake().getBytes( "ASCII" ) );
    } catch ( UnsupportedEncodingException e ) {
        throw new RuntimeException( e );
    }
}
项目:quorrabot    文件:SocketChannelIOHelper.java   
/**
 * Returns whether the whole outQueue has been flushed
 */
public static boolean batch(WebSocketImpl ws, ByteChannel sockchannel) throws IOException {
    ByteBuffer buffer = ws.outQueue.peek();
    WrappedByteChannel c = null;

    if (buffer == null) {
        if (sockchannel instanceof WrappedByteChannel) {
            c = (WrappedByteChannel) sockchannel;
            if (c.isNeedWrite()) {
                c.writeMore();
            }
        }
    } else {
        do {// FIXME writing as much as possible is unfair!!
            /*int written = */
            sockchannel.write(buffer);
            if (buffer.remaining() > 0) {
                return false;
            } else {
                ws.outQueue.poll(); // Buffer finished. Remove it.
                buffer = ws.outQueue.peek();
            }
        } while (buffer != null);
    }

    if (ws != null && ws.outQueue.isEmpty() && ws.isFlushAndClose() && ws.getDraft() != null && ws.getDraft().getRole() != null && ws.getDraft().getRole() == Role.SERVER) {//
        synchronized (ws) {
            ws.closeConnection();
        }
    }
    return c != null ? !((WrappedByteChannel) sockchannel).isNeedWrite() : true;
}
项目:quorrabot    文件:AbstractClientProxyChannel.java   
/**
   * @param towrap The channel to the proxy server
*
   */
  public AbstractClientProxyChannel(ByteChannel towrap) {
      super(towrap);
      try {
          proxyHandshake = ByteBuffer.wrap(buildHandShake().getBytes("ASCII"));
      } catch (UnsupportedEncodingException e) {
          throw new RuntimeException(e);
      }
  }
项目:boohee_v5.6    文件:SocketChannelIOHelper.java   
public static void writeBlocking(WebSocketImpl ws, ByteChannel channel) throws InterruptedException, IOException {
    if (!$assertionsDisabled && (channel instanceof AbstractSelectableChannel) && !((AbstractSelectableChannel) channel).isBlocking()) {
        throw new AssertionError();
    } else if ($assertionsDisabled || !(channel instanceof WrappedByteChannel) || ((WrappedByteChannel) channel).isBlocking()) {
        ByteBuffer buf = (ByteBuffer) ws.outQueue.take();
        while (buf.hasRemaining()) {
            channel.write(buf);
        }
    } else {
        throw new AssertionError();
    }
}
项目:boohee_v5.6    文件:AbstractClientProxyChannel.java   
public AbstractClientProxyChannel(ByteChannel towrap) {
    super(towrap);
    try {
        this.proxyHandshake = ByteBuffer.wrap(buildHandShake().getBytes("ASCII"));
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}
项目:NIOHttp    文件:Demo.java   
private void writeGetRequestToChannel(ByteChannel channel) throws IOException {

    Request request = new HttpRequestBuilder(this.url).closeConnection()
        .userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1").httpGet();

    sysout(request.getBytes(), "HTTP Request");
    ByteBuffer sending = ByteBuffer.allocate(request.getBytes().length);
    sending.put(request.getBytes());
    sending.flip();
    channel.write(sending);
    }
项目:MundoSK    文件:SocketChannelIOHelper.java   
/** Returns whether the whole outQueue has been flushed
 * @param ws The WebSocketImpl associated with the channels
 * @param sockchannel The channel to write to
 * @throws IOException May be thrown by {@link WrappedByteChannel#writeMore()}
 * @return returns Whether there is more data to write
 */
public static boolean batch( WebSocketImpl ws, ByteChannel sockchannel ) throws IOException {
    ByteBuffer buffer = ws.outQueue.peek();
    WrappedByteChannel c = null;

    if( buffer == null ) {
        if( sockchannel instanceof WrappedByteChannel ) {
            c = (WrappedByteChannel) sockchannel;
            if( c.isNeedWrite() ) {
                c.writeMore();
            }
        }
    } else {
        do {// FIXME writing as much as possible is unfair!!
            /*int written = */sockchannel.write( buffer );
            if( buffer.remaining() > 0 ) {
                return false;
            } else {
                ws.outQueue.poll(); // Buffer finished. Remove it.
                buffer = ws.outQueue.peek();
            }
        } while ( buffer != null );
    }

    if( ws != null && ws.outQueue.isEmpty() && ws.isFlushAndClose() && ws.getDraft() != null && ws.getDraft().getRole() != null && ws.getDraft().getRole() == Role.SERVER ) {//
        synchronized ( ws ) {
            ws.closeConnection();
        }
    }
    return c == null || !((WrappedByteChannel) sockchannel).isNeedWrite();
}
项目:MundoSK    文件:AbstractClientProxyChannel.java   
/**
 * @param towrap
 *            The channel to the proxy server
 **/
public AbstractClientProxyChannel( ByteChannel towrap ) {
    super( towrap );
    try {
        proxyHandshake = ByteBuffer.wrap( buildHandShake().getBytes( "ASCII" ) );
    } catch ( UnsupportedEncodingException e ) {
        throw new RuntimeException( e );
    }
}
项目:MundoSK    文件:DefaultSSLWebSocketServerFactory.java   
@Override
public ByteChannel wrapChannel( SocketChannel channel, SelectionKey key ) throws IOException {
    SSLEngine e = sslcontext.createSSLEngine();
    /**
     * See https://github.com/TooTallNate/Java-WebSocket/issues/466
     *
     * We remove TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 from the enabled ciphers since it is just available when you patch your java installation directly.
     * E.key. firefox requests this cipher and this causes some dcs/instable connections
     */
    List<String> ciphers = new ArrayList<String>( Arrays.asList(e.getEnabledCipherSuites()));
    ciphers.remove("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256");
    e.setEnabledCipherSuites( ciphers.toArray(new String[]{}));
    e.setUseClientMode( false );
    return new SSLSocketChannel2( channel, e, exec, key );
}
项目:libcommon    文件:AbstractChannelDataLink.java   
public AbstractClient(@NonNull final AbstractChannelDataLink parent,
    @Nullable final ByteChannel channel) {

    if (DEBUG) Log.v(TAG, "Client#コンストラクタ:channel=" + channel);
    mWeakParent = new WeakReference<AbstractChannelDataLink>(parent);
    mSenderHandler = HandlerThreadHandler.createHandler(this);
    mChannel = channel;
}
项目:libcommon    文件:ChannelHelper.java   
/**
 * ByteChannelからbooleanを読み込む
 * @param channel
 * @param work
 * @return
 * @throws IOException
 */
public static boolean readBoolean(
    @NonNull final ByteChannel channel,
    @Nullable final ByteBuffer work) throws IOException {

    final ByteBuffer buf = checkBuffer(work, 1);
    final int readBytes = channel.read(buf);
    if (readBytes != 1) throw new IOException();
    buf.clear();
    return buf.get() != 0;
}
项目:pizzascript    文件:SocketChannelIOHelper.java   
/** Returns whether the whole outQueue has been flushed */
public static boolean batch( WebSocketImpl ws, ByteChannel sockchannel ) throws IOException {
    ByteBuffer buffer = ws.outQueue.peek();
    WrappedByteChannel c = null;

    if( buffer == null ) {
        if( sockchannel instanceof WrappedByteChannel ) {
            c = (WrappedByteChannel) sockchannel;
            if( c.isNeedWrite() ) {
                c.writeMore();
            }
        }
    } else {
        do {// FIXME writing as much as possible is unfair!!
            /*int written = */sockchannel.write( buffer );
            if( buffer.remaining() > 0 ) {
                return false;
            } else {
                ws.outQueue.poll(); // Buffer finished. Remove it.
                buffer = ws.outQueue.peek();
            }
        } while ( buffer != null );
    }

    if( ws != null && ws.outQueue.isEmpty() && ws.isFlushAndClose() && ws.getDraft() != null && ws.getDraft().getRole() != null && ws.getDraft().getRole() == Role.SERVER ) {//
        synchronized ( ws ) {
            ws.closeConnection();
        }
    }
    return c != null ? !( (WrappedByteChannel) sockchannel ).isNeedWrite() : true;
}
项目:libcommon    文件:ChannelHelper.java   
/**
 * ByteChannelからcharを読み込む
 * @param channel
 * @param work
 * @return
 * @throws IOException
 */
public static char readChar(@NonNull final ByteChannel channel,
    @Nullable final ByteBuffer work) throws IOException {

    final ByteBuffer buf = checkBuffer(work, 2);
    final int readBytes = channel.read(buf);
    if (readBytes != 2) throw new IOException();
    buf.clear();
    return buf.getChar();
}
项目:libcommon    文件:ChannelHelper.java   
/**
 * ByteChannelからshortを読み込む
 * @param channel
 * @param work
 * @return
 * @throws IOException
 */
public static short readShort(@NonNull final ByteChannel channel,
    @Nullable final ByteBuffer work) throws IOException {

    final ByteBuffer buf = checkBuffer(work, 2);
    final int readBytes = channel.read(buf);
    if (readBytes != 2) throw new IOException();
    buf.clear();
    return buf.getShort();
}
项目:libcommon    文件:ChannelHelper.java   
/**
 * ByteChannelからintを読み込む
 * @param channel
 * @param work
 * @return
 * @throws IOException
 */
public static int readInt(@NonNull final ByteChannel channel,
    @Nullable final ByteBuffer work) throws IOException {

    final ByteBuffer buf = checkBuffer(work, 4);
    final int readBytes = channel.read(buf);
    if (readBytes != 4) throw new IOException();
    buf.clear();
    return buf.getInt();
}
项目:libcommon    文件:ChannelHelper.java   
/**
 * ByteChannelからlongを読み込む
 * @param channel
 * @param work
 * @return
 * @throws IOException
 */
public static long readLong(@NonNull final ByteChannel channel,
    @Nullable final ByteBuffer work) throws IOException {

    final ByteBuffer buf = checkBuffer(work, 8);
    final int readBytes = channel.read(buf);
    if (readBytes != 8) throw new IOException();
    buf.clear();
    return buf.getLong();
}
项目:libcommon    文件:ChannelHelper.java   
/**
 * ByteChannelからfloatを読み込む
 * @param channel
 * @return
 * @throws IOException
 */
public static float readFloat(@NonNull final ByteChannel channel)
    throws IOException {

    final ByteBuffer buf = ByteBuffer.allocate(4);
    final int readBytes = channel.read(buf);
    if (readBytes != 4) throw new IOException();
    buf.clear();
    return buf.getFloat();
}
项目:libcommon    文件:ChannelHelper.java   
/**
 * ByteChannelからdoubleを読み込む
 * @param channel
 * @return
 * @throws IOException
 */
public static double readDouble(@NonNull final ByteChannel channel,
    @Nullable final ByteBuffer work) throws IOException {

    final ByteBuffer buf = checkBuffer(work, 8);
    final int readBytes = channel.read(buf);
    if (readBytes != 8) throw new IOException();
    buf.clear();
    return buf.getDouble();
}
项目:libcommon    文件:ChannelHelper.java   
/**
 * ByteChannelからboolean配列を読み込む
 * @param channel
 * @return
 * @throws IOException
 */
public static boolean[] readBooleanArray(@NonNull final ByteChannel channel)
    throws IOException {

    final int n = readInt(channel);
    final ByteBuffer buf = ByteBuffer.allocate(n);
    final int readBytes = channel.read(buf);
    if (readBytes != n) throw new IOException();
    buf.clear();
    final boolean[] result = new boolean[n];
    for (int i = 0; i < n; i++) {
        result[i] = buf.get() != 0;
    }
    return result;
}
项目:spring-boot-concourse    文件:SocketTargetServerConnection.java   
@Override
public ByteChannel open(int socketTimeout) throws IOException {
    SocketAddress address = new InetSocketAddress(this.portProvider.getPort());
    logger.trace("Opening tunnel connection to target server on " + address);
    SocketChannel channel = SocketChannel.open(address);
    channel.socket().setSoTimeout(socketTimeout);
    return new TimeoutAwareChannel(channel);
}
项目:libcommon    文件:ChannelHelper.java   
/**
 * ByteChannelからByteBufferを読み込む
 * @param channel
 * @param readBuf
 * @param canReAllocate trueなら 指定したreadBufのremainingが読み込むサイズよりも小さい場合は
 *                      IOExceptionを投げる、falseなら必要な分を確保し直す
 * @return 読み込めた時はpositionは元のまま(読んだデータの先頭), limitをデータの最後に変更して返す
 * canReAllocate=falseなら元のreadBufとは異なるByteBufferを返すかもしれない
 * IOExceptionを投げた時は内容・position,limitは不定
 * @throws IOException
 */
public static ByteBuffer readByteBuffer(@NonNull final ByteChannel channel,
    @Nullable final ByteBuffer readBuf, final boolean canReAllocate)
        throws IOException {

    final int n = readInt(channel);
    final int pos = readBuf != null ? readBuf.position() : 0;
    ByteBuffer buf = readBuf;
    if ((buf == null) || (buf.remaining() < n)) {
        if (canReAllocate) {
            if (buf == null) {
                buf = ByteBuffer.allocateDirect(n);
            } else {
                final ByteBuffer temp = ByteBuffer.allocateDirect(
                    readBuf.limit() + n);
                buf.flip();
                temp.put(buf);
                buf = temp;
            }
        } else {
            throw new IOException();
        }
    }
    buf.limit(pos + n);
    final int readBytes = channel.read(buf);
    if (readBytes != n) throw new IOException();
    buf.position(pos);
    buf.limit(pos + n);
    return buf;
}