欢迎光临
我们一直在努力

基于NIO实现客户端通过HTTP协议访问WEB站点-JSP教程,资料/其它

建站超值云服务器,限时71元/月

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

}

}

}

}

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » 基于NIO实现客户端通过HTTP协议访问WEB站点-JSP教程,资料/其它
分享到: 更多 (0)

相关推荐

  • 暂无文章