Java Reference
In-Depth Information
WritableByteChannel out = Channels . newChannel ( System . out );
while ( client . read ( buffer ) != - 1 ) {
buffer . flip ();
out . write ( buffer );
buffer . clear ();
}
} catch ( IOException ex ) {
ex . printStackTrace ();
}
}
}
Here's the output from a sample run:
$ java ChargenClient rama.poly.edu
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefg
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefgh
"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghi
#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghij
$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijk
%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijkl
&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklm
...
So far, this is just an alternate vision of a program that could have easily been written
using streams. The really new feature comes if you want the client to do something
besides copying all input to output. You can run this connection in either blocking or
nonblocking mode in which read() returns immediately even if no data is available.
This allows the program to do something else before it attempts to read. It doesn't have
to wait for a slow network connection. To change the blocking mode, pass true (block)
or false (don't block) to the configureBlocking() method. Let's make this connection
nonblocking:
client . configureBlocking ( false );
In nonblocking mode, read() may return 0 because it doesn't read anything. Therefore,
the loop needs to be a little different:
while ( true ) {
// Put whatever code here you want to run every pass through the loop
// whether anything is read or not
int n = client . read ( buffer );
if ( n > 0 ) {
buffer . flip ();
out . write ( buffer );
buffer . clear ();
} else if ( n == - 1 ) {
// This shouldn't happen unless the server is misbehaving.
break ;
}
}
Search WWH ::




Custom Search