使用java.nio读取网页的程序

 

package test;

import java.nio.channels.*;
import java.net.*;
import java.io.*;
import java.util.*;
import java.nio.*;

public class NIOT4{


 private static void client(){
  try{
  Selector selector=Selector.open();
  InetSocketAddress isa=new InetSocketAddress("www.ah.xinhuanet.com",80 );
  SocketChannel sc=SocketChannel.open(isa);
  sc.configureBlocking(false);
  sc.register(selector, SelectionKey.OP_WRITE|SelectionKey.OP_READ);
  int keyn;
  while((keyn=selector.select())>0){
   Set readykey=selector.selectedKeys();
   Iterator it=readykey.iterator();
   while(it.hasNext()){
    SelectionKey skey=(SelectionKey)it.next();
    it.remove();
    SocketChannel scc=(SocketChannel)skey.channel();
    
    if((skey.readyOps()&SelectionKey.OP_WRITE)==SelectionKey.OP_WRITE){
      String head="GET / HTTP/1.1/r/n" +
      "Host: www.ah.xinhuanet.com/r/n " +
      "Connection:close/r/n"+
      "/r/n";
      ByteBuffer bbf=ByteBuffer.wrap(head.getBytes());
      scc.write(bbf);
      skey.interestOps(SelectionKey.OP_READ);
    }else if((skey.readyOps()&SelectionKey.OP_READ)==SelectionKey.OP_READ){
     ByteBuffer bff=ByteBuffer.allocate(512);
     String str=null;
     byte [] byt;
     while(true){
     int n=scc.read(bff);
     if(n>0){
      bff.flip();
      byt=new byte[bff.limit()];
      bff.get(byt);
      System.out.println(new String(byt));
         bff.clear();
     }else if(n==-1){
      break;
     }
    }
     scc.close();
     skey.cancel();
     
    }
    
   }
  }
  }catch(IOException e){
   e.printStackTrace();
  }
 }
 
 public static void main(String[] args) {
  client();

 }

}

你可能感兴趣的:(使用java.nio读取网页的程序)