Java Reference
In-Depth Information
client
.
write
(
output
);
}
}
catch
(
IOException
ex
)
{
key
.
cancel
();
try
{
key
.
channel
().
close
();
}
catch
(
IOException
cex
)
{}
}
}
}
}
}
View Buffers
If you know the
ByteBuffer
read from a
SocketChannel
contains nothing but elements
of one particular primitive data type, it may be worthwhile to create a
view buffer
. This
is a new
Buffer
object of appropriate type (e.g.,
DoubleBuffer
,
IntBuffer
, etc.), that
draws its data from an underlying
ByteBuffer
beginning with the current position.
Changes to the view buffer are reflected in the underlying buffer and vice versa. How‐
ever, each buffer has its own independent limit, capacity, mark, and position. View
buffers are created with one of these six methods in
ByteBuffer
:
public
abstract
ShortBuffer
asShortBuffer
()
public
abstract
CharBuffer
asCharBuffer
()
public
abstract
IntBuffer
asIntBuffer
()
public
abstract
LongBuffer
asLongBuffer
()
public
abstract
FloatBuffer
asFloatBuffer
()
public
abstract
DoubleBuffer
asDoubleBuffer
()
For example, consider a client for the
Intgen
protocol. This protocol is only going to
read
int
s, so it may be helpful to use an
IntBuffer
rather than a
ByteBuffer
.
Example 11-4
demonstrates. For variety, this client is synchronous and blocking, but it
still uses channels and buffers.
Example 11-4. Intgen client
import
java.nio.*
;
import
java.nio.channels.*
;
import
java.net.*
;
import
java.io.IOException
;
public
class
IntgenClient
{
public
static
int
DEFAULT_PORT
=
1919
;
public
static
void
main
(
String
[]
args
)
{
if
(
args
.
length
==
0
)
{