Java Reference
In-Depth Information
You might choose this more roundabout approach in order to configure various options
on the channel and/or the socket before connecting. Specifically, use this approach if
you want to open the channel without blocking:
SocketChannel
channel
=
SocketChannel
.
open
();
SocketAddress
address
=
new
InetSocketAddress
(
"www.cafeaulait.org"
,
80
);
channel
.
configureBlocking
(
false
);
channel
.
connect
();
With a nonblocking channel, the
connect()
method returns immediately, even before
the connection is established. The program can do other things while it waits for the
operating system to finish the connection. However, before it can actually use the con‐
nection, the program must call
finishConnect()
:
public
abstract
boolean
finishConnect
()
throws
IOException
(This is only necessary in nonblocking mode. For a blocking channel, this method
returns true immediately.) If the connection is now ready for use,
finishConnect()
returns
true
. If the connection has not been established yet,
finishConnect()
returns
false
. Finally, if the connection could not be established, for instance because the net‐
work is down, this method throws an exception.
If the program wants to check whether the connection is complete, it can call these two
methods:
public
abstract
boolean
isConnected
()
public
abstract
boolean
isConnectionPending
()
The
isConnected()
method returns
true
if the connection is open. The
isConnection
Pending()
method returns
true
if the connection is still being set up but is not yet open.
Reading
To read from a
SocketChannel
, first create a
ByteBuffer
the channel can store data in.
Then pass it to the
read()
method:
public
abstract
int
read
(
ByteBuffer
dst
)
throws
IOException
The channel fills the buffer with as much data as it can, then returns the number of bytes
it put there. When it encounters the end of stream, the channel fills the buffer with any
remaining bytes and then returns -1 on the next call to
read()
. If the channel is blocking,
this method will read at least one byte or return -1 or throw an exception. If the channel
is nonblocking, however, this method may return 0.
Because the data is stored into the buffer at the current position, which is updated
automatically as more data is added, you can keep passing the same buffer to the
read()
method until the buffer is filled. For example, this loop will read until the buffer is filled
or the end of stream is detected:
while
(
buffer
.
hasRemaining
()
&&
channel
.
read
(
buffer
)
!=
-
1
)
;