import java.net.InetSocketAddress ;
import java.io.* ;
import java.nio.ByteBuffer ;
import java.nio.channels.* ;
public class NIOBrowser {
public static void main(String [] args) throws IOException {
int BUF_SIZE = 256 ;
ByteBuffer buffer = ByteBuffer.allocateDirect(BUF_SIZE) ;
// Uses inaccessible system memory for storage
InetSocketAddress addr =
new InetSocketAddress("www.grid2004.org", 80) ;
SocketChannel sc = SocketChannel.open(addr) ;
// Create a socket channel.
String request = "GET /spring2004/index.html HTTP/1.1\r\n" +
"Host: www.grid2004.org\r\n\r\n" ;
buffer.put(request.getBytes()) ;
buffer.flip() ;
sc.write(buffer) ;
buffer.clear() ;
FileOutputStream fs = new FileOutputStream("index.html") ;
FileChannel fc = fs.getChannel() ;
while(sc.read(buffer) != -1) {
buffer.flip() ;
while(buffer.hasRemaining())
fc.write(buffer) ;
buffer.clear() ;
}
}
}