首 页文章中心下载中心繁體中文
设为首页
加入收藏
联系我们
您当前的位置:开源盛世-源代码下载网 -> 文章中心 -> 其他编程 -> Java技术 -> 文章内容 退出登录 用户管理
栏目导航
· VC# 技术 · Delphi技术
· Java技术 · 通用算法
· 编程相关
热门文章
· Tab Control控件使用...
· 学生档案管理系统
· [图文] 排列组合公式
· UTF-8与GB2312之间的...
· DirectShow下载安装...
· Virtual PC 在PAE模...
· Windows2000终端服务...
· MapInfo上的GIS系统...
· kalman filter 卡尔...
· Windows2000终端服务...
相关文章
· 设计面向IE for Poc...
· 设计面向IE for Poc...
· 设计面向IE for Poc...
· 设计面向IE for Poc...
· 设计面向IE for Poc...
· 设计面向IE for Poc...
基于NIO实现客户端通过HTTP协议访问WEB站点
作者:佚名  来源:vscodes.com整理  发布时间:2005-12-16 12:59:39  发布人:Polaris

减小字体 增大字体

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



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

[] [返回上一页] [打 印] [收 藏]
 
∷相关“基于NIO实现客户端通过HTTP协议访问WEB站点”文章评论∷
(评论内容只代表网友观点,与本站立场无关!) [更多评论...]
关于本站 - 网站帮助 - 广告合作 - 下载声明 - 友情连接 - 网站地图 网站目录 鄂ICP备06007162
开源盛世 版权所有Copyright © 2003-2005 VSCodes.Com. All Rights Reserved.