Java Reference
In-Depth Information
System . out . println ( "Usage: java IntgenClient 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 ( 4 );
IntBuffer view = buffer . asIntBuffer ();
for ( int expected = 0 ; ; expected ++) {
client . read ( buffer );
int actual = view . get ();
buffer . clear ();
view . rewind ();
if ( actual != expected ) {
System . err . println ( "Expected " + expected + "; was " + actual );
break ;
}
System . out . println ( actual );
}
} catch ( IOException ex ) {
ex . printStackTrace ();
}
}
}
There's one thing to note here. Although you can fill and drain the buffers using the
methods of the IntBuffer class exclusively, data must be read from and written to the
channel using the original ByteBuffer of which the IntBuffer is a view. The SocketCh
annel class only has methods to read and write ByteBuffer s. It cannot read or write
any other kind of buffer. This also means you need to clear the ByteBuffer on each pass
through the loop or the buffer will fill up and the program will halt. The positions and
limits of the two buffers are independent and must be considered separately. Finally, if
you're working in nonblocking mode, be careful that all the data in the underlying
ByteBuffer is drained before reading or writing from the overlaying view buffer. Non‐
blocking mode provides no guarantee that the buffer will still be aligned on an int ,
double , or char . boundary following a drain. It's completely possible for a nonblocking
channel to write half the bytes of an int or a double. When using nonblocking I/O, be
sure to check for this problem before putting more data in the view buffer.
Search WWH ::




Custom Search