This is just a simple example. If you want to know the details of HTTP, please refer to my open source project 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 factory 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 (ooException e) {E.PrintStackTrace ();} while (sel.isopen ()) {Try {sel.select ();} catch (ooException 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 (buf) == -1) {sk.cancel (); Next.Close () ;