public class NioChannel extends Object implements AsynchronousByteChannel, NetworkChannel
NioChannel
An asynchronous channel for stream-oriented connecting sockets.
NIO Asynchronous socket channels are created in one of two ways. A
newly-created NioChannel
is created by invoking one of the
open
methods defined by this class. A newly-created channel is
open but not yet connected. A connected NioChannel
is created when a
connection is made to the socket of an
AsynchronousServerSocketChannel
. It is not possible to create an
asynchronous socket channel for an arbitrary, pre-existing
socket
.
A newly-created channel is connected by invoking its connect
method; once connected, a channel remains connected until it is closed.
Whether or not a socket channel is connected may be determined by invoking
its getRemoteAddress
method. An attempt to invoke
an I/O operation upon an unconnected channel will cause a
NotYetConnectedException
to be thrown.
Channels of this type are safe for use by multiple concurrent threads. They
support concurrent reading and writing, though at most one read operation and
one write operation can be outstanding at any time. If a thread initiates a
read operation before a previous read operation has completed then a
ReadPendingException
will be thrown. Similarly, an attempt to
initiate a write operation before a previous write has completed will throw a
WritePendingException
.
Socket options are configured using the
setOption
method. NIO Asynchronous
socket channels support the following options:
Additional (implementation specific) options may also be supported.
Option Name Description SO_SNDBUF
The size of the socket send buffer SO_RCVBUF
The size of the socket receive buffer SO_KEEPALIVE
Keep connection alive SO_REUSEADDR
Re-use address TCP_NODELAY
Disable the Nagle algorithm
The read
and
write
methods defined by this class allow a timeout to be specified when initiating
a read or write operation. If the timeout elapses before an operation
completes then the operation completes with the exception
InterruptedByTimeoutException
. A timeout may leave
the channel, or the underlying connection, in an inconsistent state. Where
the implementation cannot guarantee that bytes have not been read from the
channel then it puts the channel into an implementation specific
error state. A subsequent attempt to initiate a read
operation causes an unspecified runtime exception to be thrown. Similarly if
a write
operation times out and the implementation cannot guarantee
bytes have not been written to the channel then further attempts to
write
to the channel cause an unspecified runtime exception to be
thrown. When a timeout elapses then the state of the
ByteBuffer
, or the sequence of buffers, for the I/O
operation is not defined. Buffers should be discarded or at least care must
be taken to ensure that the buffers are not accessed while the channel
remains open. All methods that accept timeout parameters treat values less
than or equal to zero to mean that the I/O operation does not timeout.
Modifier and Type | Field and Description |
---|---|
protected AsynchronousSocketChannel |
channel |
static int |
OP_STATUS_CLOSED
Channel closed status code
|
static int |
OP_STATUS_ERROR
Read/write operation error code
|
static int |
OP_STATUS_NORMAL |
static int |
OP_STATUS_READ_KILLED |
static int |
OP_STATUS_READ_TIMEOUT
Read timeout status code
|
static int |
OP_STATUS_WRITE_KILLED |
static int |
OP_STATUS_WRITE_TIMEOUT
Write timeout status code
|
Modifier | Constructor and Description |
---|---|
protected |
NioChannel(AsynchronousSocketChannel channel)
Create a new instance of
NioChannel |
Modifier and Type | Method and Description |
---|---|
<A> void |
awaitRead(A attachment,
CompletionHandler<Integer,? super A> handler)
Wait for incoming data in a non-blocking mode.
|
<A> void |
awaitRead(long timeout,
TimeUnit unit,
A attachment,
CompletionHandler<Integer,? super A> handler)
Wait for incoming data in a non-blocking mode.
|
NioChannel |
bind(SocketAddress local)
Binds the channel's socket to a local address.
|
NioChannel |
bind(String hostname,
int port)
Binds the channel's socket to a local address.
|
void |
close()
Close this channel.
|
void |
close(boolean force)
Try to close this channel.
|
Future<Void> |
connect(SocketAddress remote)
Connects this channel.
|
<A> void |
connect(SocketAddress remote,
A attachment,
CompletionHandler<Void,? super A> handler)
Connects this channel.
|
protected ByteBuffer |
getBuffer() |
long |
getId() |
SocketAddress |
getLocalAddress() |
Object |
getLock() |
String |
getName()
Getter for name
|
<T> T |
getOption(SocketOption<T> name)
Returns the value of a socket option.
|
SocketAddress |
getRemoteAddress() |
Object |
getWriteLock() |
boolean |
isClosed()
Tells whether or not this channel is closed.
|
boolean |
isOpen()
Tells whether or not this channel is open.
|
boolean |
isSecure() |
static NioChannel |
open()
Opens a
NioChannel . |
static NioChannel |
open(AsynchronousChannelGroup group)
Opens an asynchronous socket channel.
|
AsynchronousChannelProvider |
provider()
Returns the provider that created this channel.
|
Future<Integer> |
read(ByteBuffer dst)
Deprecated.
|
<A> void |
read(ByteBuffer[] dsts,
int offset,
int length,
long timeout,
TimeUnit unit,
A attachment,
CompletionHandler<Long,? super A> handler)
Reads a sequence of bytes from this channel into a subsequence of the
given buffers.
|
<A> void |
read(ByteBuffer dst,
A attachment,
CompletionHandler<Integer,? super A> handler) |
<A> void |
read(ByteBuffer dst,
long timeout,
TimeUnit unit,
A attachment,
CompletionHandler<Integer,? super A> handler)
Reads a sequence of bytes from this channel into the given buffer.
|
int |
readBytes(ByteBuffer dst)
Read a sequence of bytes in blocking mode.
|
int |
readBytes(ByteBuffer dst,
long timeout,
TimeUnit unit)
Read a sequence of bytes in blocking mode
|
protected void |
reset()
Reset the internal buffer
|
protected int |
reset(ByteBuffer dst)
Retrieve data, if any, from the internal buffer, put it in the
dst buffer and clear the internal buffer
|
<T> NioChannel |
setOption(SocketOption<T> name,
T value)
Sets the value of a socket option.
|
NioChannel |
shutdownInput()
Shutdown the connection for reading without closing the channel.
|
NioChannel |
shutdownOutput()
Shutdown the connection for writing without closing the channel.
|
Set<SocketOption<?>> |
supportedOptions()
Returns a set of the socket options supported by this channel.
|
String |
toString() |
Future<Integer> |
write(ByteBuffer src)
Deprecated.
(use writeBytes(...) instead)
|
<A> void |
write(ByteBuffer[] srcs,
int offset,
int length,
long timeout,
TimeUnit unit,
A attachment,
CompletionHandler<Long,? super A> handler)
Writes a sequence of bytes to this channel from a subsequence of the
given buffers.
|
<A> void |
write(ByteBuffer src,
A attachment,
CompletionHandler<Integer,? super A> handler) |
<A> void |
write(ByteBuffer src,
long timeout,
TimeUnit unit,
A attachment,
CompletionHandler<Integer,? super A> handler)
Writes a sequence of bytes to this channel from the given buffer.
|
int |
writeBytes(ByteBuffer src)
Writes a sequence of bytes to this channel from the given buffer.
|
int |
writeBytes(ByteBuffer src,
long timeout,
TimeUnit unit)
Write a sequence of bytes in blocking mode.
|
public static final int OP_STATUS_NORMAL
public static final int OP_STATUS_CLOSED
public static final int OP_STATUS_READ_TIMEOUT
public static final int OP_STATUS_WRITE_TIMEOUT
public static final int OP_STATUS_READ_KILLED
public static final int OP_STATUS_WRITE_KILLED
public static final int OP_STATUS_ERROR
protected AsynchronousSocketChannel channel
protected NioChannel(AsynchronousSocketChannel channel)
NioChannel
channel
- The AsynchronousSocketChannel
attached to this channelNullPointerException
- if the channel parameter is nullpublic Object getLock()
public Object getWriteLock()
public static NioChannel open(AsynchronousChannelGroup group) throws IOException
The new channel is created by invoking the
openAsynchronousSocketChannel
method on the
AsynchronousChannelProvider
that created the group. If the group
parameter is null
then the resulting channel is created by the
system-wide default provider, and bound to the default group.
group
- The group to which the newly constructed channel should be
bound, or null
for the default groupShutdownChannelGroupException
- If the channel group is shutdownIOException
- If an I/O error occurspublic static NioChannel open() throws IOException
NioChannel
.
This method returns an NioChannel
that is bound to the
default group.This method is equivalent to evaluating the
expression:
open((AsynchronousChannelGroup) null);
NioChannel
IOException
- If an I/O error occurspublic NioChannel bind(SocketAddress local) throws IOException
This method is used to establish an association between the socket and a
local address. Once an association is established then the socket remains
bound until the channel is closed. If the local
parameter has the
value null
then the socket will be bound to an address that is
assigned automatically.
bind
in interface NetworkChannel
local
- The address to bind the socket, or null
to bind the
socket to an automatically assigned socket addressAlreadyBoundException
- If the socket is already boundUnsupportedAddressTypeException
- If the type of the given address is not supportedClosedChannelException
- If the channel is closedIOException
- If some other I/O error occursSecurityException
- If a security manager is installed and it denies an
unspecified permission. An implementation of this interface
should specify any required permissions.getLocalAddress()
public NioChannel bind(String hostname, int port) throws IOException
This method is used to establish an association between the socket and a local address. Once an association is established then the socket remains bound until the channel is closed.
hostname
- the Host nameport
- The port numberAlreadyBoundException
- If the socket is already boundUnsupportedAddressTypeException
- If the type of the given address is not supportedClosedChannelException
- If the channel is closedIOException
- If some other I/O error occursIllegalArgumentException
- if the port parameter is outside the range of valid port
values, or if the hostname parameter is null.SecurityException
- If a security manager is installed and it denies an
unspecified permission. An implementation of this interface
should specify any required permissions.bind(SocketAddress)
public <A> void connect(SocketAddress remote, A attachment, CompletionHandler<Void,? super A> handler)
This method initiates an operation to connect this channel. The
handler
parameter is a completion handler that is invoked when
the connection is successfully established or connection cannot be
established. If the connection cannot be established then the channel is
closed.
This method performs exactly the same security checks as the
Socket
class. That is, if a security manager has been
installed then this method verifies that its
checkConnect
method
permits connecting to the address and port number of the given remote
endpoint.
remote
- The remote address to which this channel is to be connectedattachment
- The object to attach to the I/O operation; can be null
handler
- The handler for consuming the resultUnresolvedAddressException
- If the given remote address is not fully resolvedUnsupportedAddressTypeException
- If the type of the given remote address is not supportedAlreadyConnectedException
- If this channel is already connectedConnectionPendingException
- If a connection operation is already in progress on this
channelShutdownChannelGroupException
- If the channel group has terminatedSecurityException
- If a security manager has been installed and it does not
permit access to the given remote endpointgetRemoteAddress()
public Future<Void> connect(SocketAddress remote)
This method initiates an operation to connect this channel. This method
behaves in exactly the same manner as the
connect(SocketAddress, Object, CompletionHandler)
method except
that instead of specifying a completion handler, this method returns a
Future
representing the pending result. The Future
's
get
method returns null
on successful
completion.
remote
- The remote address to which this channel is to be connectedFuture
object representing the pending resultUnresolvedAddressException
- If the given remote address is not fully resolvedUnsupportedAddressTypeException
- If the type of the given remote address is not supportedAlreadyConnectedException
- If this channel is already connectedConnectionPendingException
- If a connection operation is already in progress on this
channelSecurityException
- If a security manager has been installed and it does not
permit access to the given remote endpointprotected void reset()
protected int reset(ByteBuffer dst)
dst
- the destination bufferpublic boolean isSecure()
protected ByteBuffer getBuffer()
public long getId()
public String getName()
public final AsynchronousChannelProvider provider()
public boolean isOpen()
Tells whether or not this channel is open.
public boolean isClosed()
Tells whether or not this channel is closed.
public void close() throws IOException
Any outstanding asynchronous operations upon this channel will complete
with the exception AsynchronousCloseException
. After a channel is
closed, further attempts to initiate asynchronous I/O operations complete
immediately with cause ClosedChannelException
.
This method otherwise behaves exactly as specified by the
Channel
interface.
close
in interface Closeable
close
in interface AutoCloseable
close
in interface AsynchronousChannel
close
in interface Channel
IOException
- If an I/O error occurspublic void close(boolean force) throws IOException
force
parameter is false, nothing will happen. This method has an
impact only if the channel is open and the force
parameter is
trueforce
- a boolean value indicating if we need to force closing the
channelIOException
@Deprecated public Future<Integer> read(ByteBuffer dst)
read
in interface AsynchronousByteChannel
public int readBytes(ByteBuffer dst) throws Exception
readBytes(dst, Integer.MAX_VALUE, TimeUnit.MILLISECONDS)
.dst
- the buffer containing the read bytesException
ExecutionException
InterruptedException
public int readBytes(ByteBuffer dst, long timeout, TimeUnit unit) throws Exception
dst
- the buffer containing the read bytestimeout
- the read timeoutunit
- the timeout unitOP_STATUS_CLOSED
if the channel is closedOP_STATUS_READ_TIMEOUT
if the operation
was timed outException
ExecutionException
InterruptedException
public <A> void read(ByteBuffer dst, A attachment, CompletionHandler<Integer,? super A> handler)
read
in interface AsynchronousByteChannel
public <A> void read(ByteBuffer dst, long timeout, TimeUnit unit, A attachment, CompletionHandler<Integer,? super A> handler)
This method initiates an asynchronous read operation to read a sequence
of bytes from this channel into the given buffer. The handler
parameter is a completion handler that is invoked when the read operation
completes (or fails). The result passed to the completion handler is the
number of bytes read or -1
if no bytes could be read because the
channel has reached end-of-stream.
If a timeout is specified and the timeout elapses before the operation
completes then the operation completes with the exception
InterruptedByTimeoutException
. Where a timeout occurs, and the
implementation cannot guarantee that bytes have not been read, or will
not be read from the channel into the given buffer, then further attempts
to read from the channel will cause an unspecific runtime exception to be
thrown.
Otherwise this method works in the same manner as the
read(ByteBuffer,Object,CompletionHandler)
method.
dst
- The buffer into which bytes are to be transferredtimeout
- The maximum time for the I/O operation to completeunit
- The time unit of the timeout
argumentattachment
- The object to attach to the I/O operation; can be null
handler
- The handler for consuming the resultIllegalArgumentException
- If the buffer is read-onlyReadPendingException
- If a read operation is already in progress on this channelNotYetConnectedException
- If this channel is not yet connectedShutdownChannelGroupException
- If the channel group has terminatedpublic <A> void read(ByteBuffer[] dsts, int offset, int length, long timeout, TimeUnit unit, A attachment, CompletionHandler<Long,? super A> handler)
handler
parameter is a completion handler that is invoked when
the read operation completes (or fails). The result passed to the
completion handler is the number of bytes read or -1
if no bytes
could be read because the channel has reached end-of-stream.
This method initiates a read of up to r bytes from this channel, where r is the total number of bytes remaining in the specified subsequence of the given buffer array, that is,
at the moment that the read is attempted.dsts[offset].remaining() + dsts[offset+1].remaining() + ... + dsts[offset+length-1].remaining()
Suppose that a byte sequence of length n is read, where 0 < n <= r. Up to the first dsts[offset].remaining() bytes of this sequence are transferred into buffer dsts[offset], up to the next dsts[offset+1].remaining() bytes are transferred into buffer dsts[offset+1], and so forth, until the entire byte sequence is transferred into the given buffers. As many bytes as possible are transferred into each buffer, hence the final position of each updated buffer, except the last updated buffer, is guaranteed to be equal to that buffer's limit. The underlying operating system may impose a limit on the number of buffers that may be used in an I/O operation. Where the number of buffers (with bytes remaining), exceeds this limit, then the I/O operation is performed with the maximum number of buffers allowed by the operating system.
If a timeout is specified and the timeout elapses before the operation
completes then it completes with the exception
InterruptedByTimeoutException
. Where a timeout occurs, and the
implementation cannot guarantee that bytes have not been read, or will
not be read from the channel into the given buffers, then further
attempts to read from the channel will cause an unspecific runtime
exception to be thrown.
dsts
- The buffers into which bytes are to be transferredoffset
- The offset within the buffer array of the first buffer into
which bytes are to be transferred; must be non-negative and no
larger than dsts.length
length
- The maximum number of buffers to be accessed; must be
non-negative and no larger than dsts.length - offset
timeout
- The maximum time for the I/O operation to completeunit
- The time unit of the timeout
argumentattachment
- The object to attach to the I/O operation; can be null
handler
- The handler for consuming the resultIndexOutOfBoundsException
- If the pre-conditions for the offset
and
length
parameter aren't metIllegalArgumentException
- If the buffer is read-onlyReadPendingException
- If a read operation is already in progress on this channelNotYetConnectedException
- If this channel is not yet connectedShutdownChannelGroupException
- If the channel group has terminatedpublic <A> void awaitRead(long timeout, TimeUnit unit, A attachment, CompletionHandler<Integer,? super A> handler)
Wait for incoming data in a non-blocking mode. The received data will be stored by default in the internal buffer (By default, just one byte).
The byte read using this method will be available for the next read operation. That is, When attempting to read after receiving a read notification saying that there is data available on this stream, the byte will be first copied in the destination byte buffer and then perform the read operation which may be a blocking or non-blocking operation. So the user does not have to do that manually.
timeout
- The maximum time for the I/O operation to completeunit
- The time unit of the timeout
argumentattachment
- The object to attach to the I/O operation; can be null
handler
- The handler for consuming the resultReadPendingException
- If a read operation is already in progress on this channelNotYetConnectedException
- If this channel is not yet connectedShutdownChannelGroupException
- If the channel group has terminatedpublic <A> void awaitRead(A attachment, CompletionHandler<Integer,? super A> handler)
Wait for incoming data in a non-blocking mode. The received data will be stored by default in the internal buffer (By default, just one byte).
This method behaves exactly in the same manner as
awaitRead(long, TimeUnit, Object, CompletionHandler)
but without
a timeout defined.
awaitRead(0L, TimeUnit.MILLISECONDS, attachment, handler);
attachment
- handler
- awaitRead(long, TimeUnit, Object, CompletionHandler)
@Deprecated public Future<Integer> write(ByteBuffer src)
write
in interface AsynchronousByteChannel
src
- The buffer from which bytes are to be retrievedFuture
containing the
number of bytes writtenAsynchronousByteChannel.write(java.nio.ByteBuffer)
public int writeBytes(ByteBuffer src) throws Exception
This method initiates an asynchronous write operation to write a sequence
of bytes to this channel from the given buffer. The method behaves in
exactly the same manner as the
writeBytes(ByteBuffer, long, TimeUnit)
with
Integer.MAX_VALUE
as a timeout and
TimeUnit.MILLISECONDS
as a time unit.
src
- The buffer from which bytes are to be retrievedWritePendingException
- If the channel does not allow more than one write to be
outstanding and a previous write has not completedExecutionException
InterruptedException
Exception
- If any other type of errors occurswriteBytes(ByteBuffer, long, TimeUnit)
public int writeBytes(ByteBuffer src, long timeout, TimeUnit unit) throws Exception
src
- the buffer containing the bytes to writetimeout
- the read timeoutunit
- the timeout unitOP_STATUS_CLOSED
if the channel is closedOP_STATUS_WRITE_TIMEOUT
if the operation
was timed outException
ExecutionException
InterruptedException
public <A> void write(ByteBuffer src, A attachment, CompletionHandler<Integer,? super A> handler)
write
in interface AsynchronousByteChannel
public <A> void write(ByteBuffer src, long timeout, TimeUnit unit, A attachment, CompletionHandler<Integer,? super A> handler)
This method initiates an asynchronous write operation to write a sequence
of bytes to this channel from the given buffer. The handler
parameter is a completion handler that is invoked when the write
operation completes (or fails). The result passed to the completion
handler is the number of bytes written.
If a timeout is specified and the timeout elapses before the operation
completes then it completes with the exception
InterruptedByTimeoutException
. Where a timeout occurs, and the
implementation cannot guarantee that bytes have not been written, or will
not be written to the channel from the given buffer, then further
attempts to write to the channel will cause an unspecific runtime
exception to be thrown.
Otherwise this method works in the same manner as the
write(ByteBuffer,Object,CompletionHandler)
method.
src
- The buffer from which bytes are to be retrievedtimeout
- The maximum time for the I/O operation to completeunit
- The time unit of the timeout
argumentattachment
- The object to attach to the I/O operation; can be null
handler
- The handler for consuming the resultWritePendingException
- If a write operation is already in progress on this channelNotYetConnectedException
- If this channel is not yet connectedShutdownChannelGroupException
- If the channel group has terminatedpublic <A> void write(ByteBuffer[] srcs, int offset, int length, long timeout, TimeUnit unit, A attachment, CompletionHandler<Long,? super A> handler)
handler
parameter is a completion handler that is invoked when
the write operation completes (or fails). The result passed to the
completion handler is the number of bytes written.
This method initiates a write of up to r bytes to this channel, where r is the total number of bytes remaining in the specified subsequence of the given buffer array, that is,
at the moment that the write is attempted.srcs[offset].remaining() + srcs[offset+1].remaining() + ... + srcs[offset+length-1].remaining()
Suppose that a byte sequence of length n is written, where 0 < n <= r. Up to the first srcs[offset].remaining() bytes of this sequence are written from buffer srcs[offset], up to the next srcs[offset+1].remaining() bytes are written from buffer srcs[offset+1], and so forth, until the entire byte sequence is written. As many bytes as possible are written from each buffer, hence the final position of each updated buffer, except the last updated buffer, is guaranteed to be equal to that buffer's limit. The underlying operating system may impose a limit on the number of buffers that may be used in an I/O operation. Where the number of buffers (with bytes remaining), exceeds this limit, then the I/O operation is performed with the maximum number of buffers allowed by the operating system.
If a timeout is specified and the timeout elapses before the operation
completes then it completes with the exception
InterruptedByTimeoutException
. Where a timeout occurs, and the
implementation cannot guarantee that bytes have not been written, or will
not be written to the channel from the given buffers, then further
attempts to write to the channel will cause an unspecific runtime
exception to be thrown.
srcs
- The buffers from which bytes are to be retrievedoffset
- The offset within the buffer array of the first buffer from
which bytes are to be retrieved; must be non-negative and no
larger than srcs.length
length
- The maximum number of buffers to be accessed; must be
non-negative and no larger than srcs.length - offset
timeout
- The maximum time for the I/O operation to completeunit
- The time unit of the timeout
argumentattachment
- The object to attach to the I/O operation; can be null
handler
- The handler for consuming the resultIndexOutOfBoundsException
- If the pre-conditions for the offset
and
length
parameter aren't metWritePendingException
- If a write operation is already in progress on this channelNotYetConnectedException
- If this channel is not yet connectedShutdownChannelGroupException
- If the channel group has terminatedpublic SocketAddress getLocalAddress() throws IOException
getLocalAddress
in interface NetworkChannel
IOException
public SocketAddress getRemoteAddress() throws IOException
IOException
public final NioChannel shutdownInput() throws IOException
Once shutdown for reading then further reads on the channel will return
-1
, the end-of-stream indication. If the input side of the
connection is already shutdown then invoking this method has no effect.
The effect on an outstanding read operation is system dependent and
therefore not specified. The effect, if any, when there is data in the
socket receive buffer that has not been read, or data arrives
subsequently, is also system dependent.
NotYetConnectedException
- If this channel is not yet connectedClosedChannelException
- If this channel is closedIOException
- If some other I/O error occurspublic final NioChannel shutdownOutput() throws IOException
Once shutdown for writing then further attempts to write to the channel
will throw ClosedChannelException
. If the output side of the
connection is already shutdown then invoking this method has no effect.
The effect on an outstanding write operation is system dependent and
therefore not specified.
NotYetConnectedException
- If this channel is not yet connectedClosedChannelException
- If this channel is closedIOException
- If some other I/O error occurspublic <T> NioChannel setOption(SocketOption<T> name, T value) throws IOException
setOption
in interface NetworkChannel
name
- The socket option namevalue
- The value of the socket option. A value of null
may be
a valid value for some socket options.UnsupportedOperationException
- If the socket option is not supported by this channelIllegalArgumentException
- If the value is not a valid value for this socket optionClosedChannelException
- If this channel is closedIOException
- If an I/O error occursStandardSocketOptions
public <T> T getOption(SocketOption<T> name) throws IOException
getOption
in interface NetworkChannel
name
- The socket optionnull
may be a
valid value for some socket options.UnsupportedOperationException
- If the socket option is not supported by this channelClosedChannelException
- If this channel is closedIOException
- If an I/O error occursStandardSocketOptions
public Set<SocketOption<?>> supportedOptions()
This method will continue to return the set of options even after the channel has been closed.
supportedOptions
in interface NetworkChannel
Copyright © 2016 JBoss by Red Hat. All rights reserved.