基于NIO实现客户端通过HTTP协议访问WEB站点

王朝java/jsp·作者佚名  2006-01-09
宽屏版  字体: |||超大  

这只是一个简单的示例,如果你想了解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));

}

}

}

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有