Java Reference
In-Depth Information
the result is the outcome of comparing the first pair of unequal elements. If one buffer
runs out of elements before an unequal element is found and the other buffer still has
elements, the shorter buffer is considered to be less than the longer buffer.
The toString() method returns strings that look something like this:
java . nio . HeapByteBuffer [ pos = 0 lim = 62 cap = 62 ]
These are primarily useful for debugging. The notable exception is CharBuffer , which
returns a string containing the remaining chars in the buffer.
Channels
Channels move blocks of data into and out of buffers to and from various I/O sources
such as files, sockets, datagrams, and so forth. The channel class hierarchy is rather
convoluted, with multiple interfaces and many optional operations. However, for pur‐
poses of network programming there are only three really important channel classes,
SocketChannel , ServerSocketChannel , and DatagramChannel ; and for the TCP con‐
nections we've talked about so far you only need the first two.
SocketChannel
The SocketChannel class reads from and writes to TCP sockets. The data must be en‐
coded in ByteBuffer objects for reading and writing. Each SocketChannel is associated
with a peer Socket object that can be used for advanced configuration, but this re‐
quirement can be ignored for applications where the default options are fine.
Connecting
The SocketChannel class does not have any public constructors. Instead, you create a
new SocketChannel object using one of the two static open() methods:
public static SocketChannel open ( SocketAddress remote ) throws IOException
public static SocketChannel open () throws IOException
The first variant makes the connection. This method blocks (i.e., the method will not
return until the connection is made or an exception is thrown). For example:
SocketAddress address = new InetSocketAddress ( "www.cafeaulait.org" , 80 );
SocketChannel channel = SocketChannel . open ( address );
The noargs version does not immediately connect. It creates an initially unconnected
socket that must be connected later using the connect() method. For example:
SocketChannel channel = SocketChannel . open ();
SocketAddress address = new InetSocketAddress ( "www.cafeaulait.org" , 80 );
channel . connect ( address );
Search WWH ::




Custom Search