这只是一个简单的示例,如果你想了解http的详细内容可参考我的一个开源项目jquickdown
/*
* created on 2005-2-1
*
* copyright by lxleaves_zhang
*/
package test;
import java.io.ioexception;
import java.net.inetsocketaddress;
import java.nio.bytebuffer;
import java.nio.channels.selectionkey;
import java.nio.channels.selector;
import java.nio.channels.socketchannel;
import java.nio.channels.spi.selectorprovider;
import java.util.iterator;
public class niotest {
public static socketchannel createsocketchannel(string host, int port)
throws ioexception {
socketchannel sc = socketchannel
.open(new inetsocketaddress(host, port));
sc.configureblocking(false);
return sc;
}
public static final string host = "www.163.com";
public static final string path = "/";
public static final int port = 80;
public static final byte[] req = ("get " + path + " http/1.0\r\nhost:"
+ host + "\r\n\r\n").getbytes();
public static void main(string[] args) {
selector sel = null;
bytebuffer buf = bytebuffer.allocate(256);
socketchannel sc[] = new socketchannel[2];
try {
sel = selectorprovider.provider().openselector();
sc[0] = createsocketchannel(host, port);
sc[1] = createsocketchannel(host, port);
buf.put(req);
buf.flip();
sc[0].write(buf);
buf.flip();
sc[1].write(buf);
sc[0].register(sel, sc[0].validops());
sc[1].register(sel, sc[1].validops());
} catch (ioexception e) {
e.printstacktrace();
}
while (sel.isopen()) {
try {
sel.select();
} catch (ioexception e) {
e.printstacktrace();
}
iterator it = sel.selectedkeys().iterator();
while (it.hasnext()) {
selectionkey sk = (selectionkey) it.next();
it.remove();
socketchannel next = (socketchannel) sk.channel();
buf.clear();
try {
// check whether finish
if (next.read(buf) == -1) {
sk.cancel();
next.close();
if (!it.hasnext()) {
sel.close();
}
}
} catch (ioexception e) {
e.printstacktrace();
}
buf.flip();
if (buf.limit() == 0)
continue;
byte b[] = new byte[buf.limit()];
buf.get(b);
// system.out.println(next == sc[0]);
if (next == sc[0])
system.out.print(new string(b));
else
system.err.print(new string(b));
}
}
}
}
