java.nio.channels.ByteChannel Java Examples

The following examples show how to use java.nio.channels.ByteChannel. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: IntegrationSocketFactory.java    From nanofix with Apache License 2.0 6 votes vote down vote up
@Override
public void createSocketOnOutgoingConnection(final InetSocketAddress socketAddress, final SocketEstablishedCallback socketEstablishedCallback)
{
    final ByteChannel byteChannel = createByteChannel(readableByteChannel, writableByteChannel);
    executorService.submit(new Runnable()
    {
        @Override
        public void run()
        {
            try
            {
                socketEstablishedCallback.onSocketEstablished(new StubSocketChannel(byteChannel));
            }
            catch (RuntimeException e)
            {
                System.err.println("Exception thrown: ");
                e.printStackTrace(System.err);
            }
        }
    });
}
 
Example #2
Source File: ChannelEndPoint.java    From IoTgo_Android_App with MIT License 6 votes vote down vote up
public ChannelEndPoint(ByteChannel channel) throws IOException
{
    super();
    this._channel = channel;
    _socket=(channel instanceof SocketChannel)?((SocketChannel)channel).socket():null;
    if (_socket!=null)
    {
        _local=(InetSocketAddress)_socket.getLocalSocketAddress();
        _remote=(InetSocketAddress)_socket.getRemoteSocketAddress();
        _maxIdleTime=_socket.getSoTimeout();
    }
    else
    {
        _local=_remote=null;
    }
}
 
Example #3
Source File: ChannelHelper.java    From libcommon with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
	}
}
 
Example #4
Source File: ChannelHelper.java    From libcommon with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
	}
}
 
Example #5
Source File: ChannelEndPoint.java    From IoTgo_Android_App with MIT License 6 votes vote down vote up
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;
    }
}
 
Example #6
Source File: WebSocketClient.java    From WebSocket-for-Android with Apache License 2.0 6 votes vote down vote up
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();
    }
}
 
Example #7
Source File: DefaultSSLWebSocketServerFactory.java    From ans-android-sdk with GNU General Public License v3.0 6 votes vote down vote up
@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.g. 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[ciphers.size()]));
    e.setUseClientMode(false);
    return new SSLSocketChannel2(channel, e, exec, key);
}
 
Example #8
Source File: WebSocketClient.java    From IoTgo_Android_App with MIT License 6 votes vote down vote up
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();
    }
}
 
Example #9
Source File: FileSystemHttpFile.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
protected int read(ByteChannel src, ByteBuf dst) throws IOException {
    if (src instanceof ScatteringByteChannel) {
        return dst.writeBytes((ScatteringByteChannel) src, dst.writableBytes());
    }

    final int readBytes = src.read(dst.nioBuffer(dst.writerIndex(), dst.writableBytes()));
    if (readBytes > 0) {
        dst.writerIndex(dst.writerIndex() + readBytes);
    }
    return readBytes;
}
 
Example #10
Source File: ChannelHelper.java    From libcommon with Apache License 2.0 5 votes vote down vote up
/**
 * ByteChannelへ書き込む
 * @param channel
 * @param value
 * @param work
 * @throws IOException
 */
public static void write(@NonNull final ByteChannel channel,
	final short value,
	@Nullable final ByteBuffer work) throws IOException {
	
	final ByteBuffer buf = checkBuffer(work, 2);
	buf.putShort(value);
	buf.flip();
	channel.write(buf);
}
 
Example #11
Source File: ChannelHelper.java    From libcommon with Apache License 2.0 5 votes vote down vote up
/**
 * ByteChannelへ書き込む
 * @param channel
 * @param value
 * @param work
 * @throws IOException
 */
public static void write(@NonNull final ByteChannel channel,
	@NonNull final double[] value,
	@Nullable final ByteBuffer work) throws IOException {
	
	final int n = value.length;
	write(channel, n, work);
	final ByteBuffer buf = checkBuffer(work, n * 8);
	for (int i = 0; i < n; i++) {
		buf.putDouble(value[i]);
	}
	buf.flip();
	channel.write(buf);
}
 
Example #12
Source File: SocketChannelIOHelper.java    From ans-android-sdk with GNU General Public License v3.0 5 votes vote down vote up
/** 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();
}
 
Example #13
Source File: ChannelHelper.java    From libcommon with Apache License 2.0 5 votes vote down vote up
/**
 * ByteChannelへ書き込む
 * @param channel
 * @param value
 * @param work
 * @throws IOException
 */
public static void write(@NonNull final ByteChannel channel,
	final float value,
	@Nullable final ByteBuffer work) throws IOException {
	
	final ByteBuffer buf = checkBuffer(work, 4);
	buf.putFloat(value);
	buf.flip();
	channel.write(buf);
}
 
Example #14
Source File: SocketChannelIOHelper.java    From RipplePower with Apache License 2.0 5 votes vote down vote up
/** 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();
}
 
Example #15
Source File: BlockFileTableSet.java    From emodb with Apache License 2.0 5 votes vote down vote up
/**
 * Loads the data from a previous flush into the buffer if it hasn't been loaded already.
 */
private void ensureLoaded()
        throws IOException {
    if (!_loaded) {
        if (_backingFile != null) {
            _log.debug("Loading buffer for index {} from {}", _startIndex, _backingFile);
            try (ByteChannel in = Files.newByteChannel(_backingFile, READ)) {
                in.read(_buffer);
            }
        }
        _loaded = true;
    }
}
 
Example #16
Source File: ChannelHelper.java    From libcommon with Apache License 2.0 5 votes vote down vote up
/**
 * ByteChannelへ書き込む
 * @param channel
 * @param value
 * @param work
 * @throws IOException
 */
public static void write(@NonNull final ByteChannel channel,
	@NonNull final boolean[] value,
	@Nullable final ByteBuffer work) throws IOException {
	
	final int n = value.length;
	write(channel, n, work);
	final ByteBuffer buf = checkBuffer(work, n);
	for (int i = 0; i < n; i++) {
		buf.put((byte)(value[i] ? 1 : 0));
	}
	buf.flip();
	channel.write(buf);
}
 
Example #17
Source File: ChannelHelper.java    From libcommon with Apache License 2.0 5 votes vote down vote up
/**
 * ByteChannelへ書き込む
 * @param channel
 * @param value
 * @throws IOException
 */
public static void write(@NonNull final ByteChannel channel,
	@NonNull final byte[] value) throws IOException {
	
	write(channel, value.length);
	channel.write(ByteBuffer.wrap(value));
}
 
Example #18
Source File: ChannelHelper.java    From libcommon with Apache License 2.0 5 votes vote down vote up
/**
 * ByteChannelへ書き込む
 * @param channel
 * @param value
 * @param work
 * @throws IOException
 */
public static void write(@NonNull final ByteChannel channel,
	@NonNull final char[] value,
	@Nullable final ByteBuffer work) throws IOException {
	
	final int n = value.length;
	write(channel, n, work);
	final ByteBuffer buf = checkBuffer(work, n * 2);
	for (int i = 0; i < n; i++) {
		buf.putChar(value[i]);
	}
	buf.flip();
	channel.write(buf);
}
 
Example #19
Source File: ChannelHelper.java    From libcommon with Apache License 2.0 5 votes vote down vote up
/**
 * ByteChannelへ書き込む
 * @param channel
 * @param value
 * @param work
 * @throws IOException
 */
public static void write(@NonNull final ByteChannel channel,
	final char value,
	@Nullable final ByteBuffer work) throws IOException {
	
	final ByteBuffer buf = checkBuffer(work, 2);
	buf.putChar(value);
	buf.flip();
	channel.write(buf);
}
 
Example #20
Source File: ChannelHelper.java    From libcommon with Apache License 2.0 5 votes vote down vote up
/**
 * ByteChannelへ書き込む
 * @param channel
 * @param value
 * @param work
 * @throws IOException
 */
public static void write(@NonNull final ByteChannel channel,
	@NonNull final short[] value,
	@Nullable final ByteBuffer work) throws IOException {
	
	final int n = value.length;
	write(channel, n, work);
	final ByteBuffer buf = checkBuffer(work, n * 2);
	for (int i = 0; i < n; i++) {
		buf.putShort(value[i]);
	}
	buf.flip();
	channel.write(buf);
}
 
Example #21
Source File: WebSocketClient.java    From WebSocket-for-Android with Apache License 2.0 5 votes vote down vote up
public void handshakeFailed(Throwable ex)
{
    try
    {
        ByteChannel channel=null;
        synchronized (this)
        {
            if (_channel!=null)
            {
                channel=_channel;
                _channel=null;
                _exception=ex;
            }
        }

        if (channel!=null)
        {
            if (ex instanceof ProtocolException)
                closeChannel(channel,WebSocketConnectionRFC6455.CLOSE_PROTOCOL,ex.getMessage());
            else
                closeChannel(channel,WebSocketConnectionRFC6455.CLOSE_NO_CLOSE,ex.getMessage());
        }
    }
    finally
    {
        _done.countDown();
    }
}
 
Example #22
Source File: ChannelHelper.java    From libcommon with Apache License 2.0 5 votes vote down vote up
/**
 * ByteChannelからbyte配列を読み込む
 * @param channel
 * @return
 * @throws IOException
 */
public static byte[] readByteArray(@NonNull final ByteChannel channel)
	throws IOException {
	
	final int n = readInt(channel);
	final byte[] result = new byte[n];
	final ByteBuffer buf = ByteBuffer.wrap(result);
	final int readBytes = channel.read(buf);
	if (readBytes != n) throw new IOException();
	return result;
}
 
Example #23
Source File: ChannelHelper.java    From libcommon with Apache License 2.0 5 votes vote down vote up
/**
 * ByteChannelからStringを読み込む
 * @param channel
 * @return
 * @throws IOException
 */
public static String readString(@NonNull final ByteChannel channel)
	throws IOException {
	
	final int bytes = readInt(channel);
	final byte[] buf = new byte[bytes];
	final ByteBuffer b = ByteBuffer.wrap(buf);
	final int readBytes = channel.read(b);
	if (readBytes != bytes) throw new IOException();
	return new String(buf, CharsetsUtils.UTF8);
}
 
Example #24
Source File: ChannelHelper.java    From libcommon with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
}
 
Example #25
Source File: ClientTlsChannel.java    From tls-channel with MIT License 5 votes vote down vote up
private ClientTlsChannel(
    ByteChannel underlying,
    SSLEngine engine,
    Consumer<SSLSession> sessionInitCallback,
    boolean runTasks,
    BufferAllocator plainBufAllocator,
    BufferAllocator encryptedBufAllocator,
    boolean releaseBuffers,
    boolean waitForCloseNotifyOnClose) {
  if (!engine.getUseClientMode())
    throw new IllegalArgumentException("SSLEngine must be in client mode");
  this.underlying = underlying;
  TrackingAllocator trackingPlainBufAllocator = new TrackingAllocator(plainBufAllocator);
  TrackingAllocator trackingEncryptedAllocator = new TrackingAllocator(encryptedBufAllocator);
  impl =
      new TlsChannelImpl(
          underlying,
          underlying,
          engine,
          Optional.empty(),
          sessionInitCallback,
          runTasks,
          trackingPlainBufAllocator,
          trackingEncryptedAllocator,
          releaseBuffers,
          waitForCloseNotifyOnClose);
}
 
Example #26
Source File: ChannelHelper.java    From libcommon with Apache License 2.0 5 votes vote down vote up
/**
 * ByteChannelからfloatを読み込む
 * @param channel
 * @return
 * @throws IOException
 */
public static float readFloat(@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.getFloat();
}
 
Example #27
Source File: ChannelHelper.java    From libcommon with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
}
 
Example #28
Source File: WebSocketClient.java    From IoTgo_Android_App with MIT License 5 votes vote down vote up
private WebSocketFuture(WebSocket websocket, URI uri, WebSocketClient client, ByteChannel channel)
{
    _websocket=websocket;
    _uri=uri;
    _client=client;
    _channel=channel;
}
 
Example #29
Source File: ChannelHelper.java    From libcommon with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
}
 
Example #30
Source File: ChannelHelper.java    From libcommon with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
}