概述
2019独角兽企业重金招聘Python工程师标准>>>
代码非常短,注释都在代码里了,相信都能理解
package com.rock.nio;
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.util.Iterator;
import java.util.Set;
public class NioHttp2 {
public static void main(String[] args) throws Exception {
Selector selector = Selector.open();
InetSocketAddress remoteAddress = new InetSocketAddress("chushu.la", 80);
// 调用open的静态方法创建连接指定的主机的SocketChannel
SocketChannel socketChangel = SocketChannel.open(remoteAddress);
// 设置该sc已非阻塞的方式工作
socketChangel.configureBlocking(false);
// 将SocketChannel对象注册到指定的Selector
socketChangel.register(selector, SelectionKey.OP_READ);
sendMessage(socketChangel, createHttpMsg());
boolean remoteConnClosed = false;
while (!remoteConnClosed) {
int n = selector.select(1000*60);//设置超时为1分钟
if (n <= 0) {
break;//
}
Set<SelectionKey> selectedKeys = selector.selectedKeys();
Iterator<SelectionKey> iter = selectedKeys.iterator();
while (iter.hasNext()) {
SelectionKey key = iter.next();
if (key.isReadable()) {
ByteBuffer buffer = ByteBuffer.allocate(1024);//如果读取的数据大于1024, 则下次调用 selector.select 的数值还会大于0
SocketChannel client = (SocketChannel) key.channel();
int num = client.read(buffer);
while(num > 0){//如果num = 0, 表示读取不到远端数据,可能是远端网速慢或者其他网络原因, 下次selector.select返回时可再读; 如果num=-1,表示远端关闭了连接。
client.read(buffer);
String reString = new String(buffer.array(), "utf-8");
System.out.print(reString);
num = client.read(buffer);
}
if(num == -1){//远程连接主动关闭
System.out.println("remote server close connection~~");
client.close();
key.cancel()
remoteConnClosed = true;
}
}
//这里必须移除掉该selectionKey, 否则下次select调用时还会存在
iter.remove();
}
}
}
private static String createHttpMsg() {
StringBuffer sBuffer = new StringBuffer();
sBuffer.append("GET / HTTP/1.1").append("rn");
sBuffer.append("Host: chushu.la").append("rn");
// sBuffer.append("Connection: Closed");
sBuffer.append("Connection: keep-alive");
sBuffer.append("rn").append("rn");
return sBuffer.toString();
}
public static void sendMessage(SocketChannel client, String msg)throws Exception {
ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
client.write(buffer);
}
}
转载于:https://my.oschina.net/rock117/blog/1476613
最后
以上就是仁爱帅哥为你收集整理的java nio select 实现 httpclient的全部内容,希望文章能够帮你解决java nio select 实现 httpclient所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复