java nio select 实现 httpclient

代码非常短,注释都在代码里了,相信都能理解

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);
    }
}

 

转载于:https://my.oschina.net/rock117/blog/1476613

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值