代码非常短,注释都在代码里了,相信都能理解
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("\r\n");
sBuffer.append("Host: chushu.la").append("\r\n");
// sBuffer.append("Connection: Closed");
sBuffer.append("Connection: keep-alive");
sBuffer.append("\r\n").append("\r\n");
return sBuffer.toString();
}
public static void sendMessage(SocketChannel client, String msg)throws Exception {
ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
client.write(buffer);
}
}