Java Reference
In-Depth Information
buffer
.
flip
();
output
.
write
(
buffer
);
You don't have to tell the output channel how many bytes to write. Buffers keep track
of how many bytes they contain. However, in general, the output channel is not guar‐
anteed to write all the bytes in the buffer. In this specific case, though, it's a blocking
channel and it will either do so or throw an
IOException
.
You shouldn't create a new buffer for each read and write. That would kill the perfor‐
mance. Instead, reuse the existing buffer. You'll need to clear the buffer before reading
into it again:
buffer
.
clear
();
This is a little different than flipping. Flipping leaves the data in the buffer intact, but
prepares it for writing rather than reading. Clearing resets the buffer to a pristine state.
(Actually that's a tad simplistic. The old data is still present; it's not overwritten, but it
will be overwritten with new data read from the source as soon as possible.)
Example 11-1
puts this together into a complete client. Because chargen is by design an
endless protocol, you'll need to kill the program using Ctrl-C.
Example 11-1. A channel-based chargen client
import
java.nio.*
;
import
java.nio.channels.*
;
import
java.net.*
;
import
java.io.IOException
;
public
class
ChargenClient
{
public
static
int
DEFAULT_PORT
=
19
;
public
static
void
main
(
String
[]
args
)
{
if
(
args
.
length
==
0
)
{
System
.
out
.
println
(
"Usage: java ChargenClient host [port]"
);
return
;
}
int
port
;
try
{
port
=
Integer
.
parseInt
(
args
[
1
]);
}
catch
(
RuntimeException
ex
)
{
port
=
DEFAULT_PORT
;
}
try
{
SocketAddress
address
=
new
InetSocketAddress
(
args
[
0
],
port
);
SocketChannel
client
=
SocketChannel
.
open
(
address
);
ByteBuffer
buffer
=
ByteBuffer
.
allocate
(
74
);