关于NIO中的selector

wy65 发布于 2014/10/10 15:31
阅读 279
收藏 0

开源之夏第三届火热来袭,高校学生参与赢万元奖金!>>>

今天写的一个小demo:

Selector selector = Selector.open();
					
String host = "http://www.ujs.edu.cn";
URL url= new java.net.URL(host);
int port = 0;
if(url.getPort() == -1){
	port = 80;
}
System.out.println("port:"+port);
					
InetSocketAddress addr = new InetSocketAddress(url.getHost(),port);
SocketChannel sc = SocketChannel.open();
sc.configureBlocking(false);
sc.connect(addr);
sc.register(selector, SelectionKey.OP_CONNECT, url);
System.out.println("Initiating connection");
					
ByteBuffer buffer = ByteBuffer.allocate(2048);
//请求消息头
StringBuilder request = new StringBuilder(100);
request.append("GET / HTTP/1.1\r\n");
request.append("Connection: keep-alive\r\n");
request.append("User-Agent: Mozilla/5.0 (Windows NT 5.1)\r\n");
request.append("Accept: text/html\r\n");
					
while(true){
	System.out.println("waitting..");
	int n = selector.select(10);
	if(n == 0) continue;
	Iterator<SelectionKey> it = selector.selectedKeys().iterator();
	while(it.hasNext()){
		SelectionKey key = it.next();

		if(key.isConnectable()){
			System.out.println("Connection established");
			SocketChannel sc1 = (SocketChannel) key.channel();
			buffer.clear();
			buffer = buffer.put(request.toString().getBytes("ISO-8859-1"));
			buffer.flip();
								
			sc1.write(buffer);//程序在这报NotYetConnectedException
			//将感兴趣操作设定为read
			key.interestOps(SelectionKey.OP_READ);
		} //可读取 
		if(key.isReadable()){ System.out.println("ready to read");
			SocketChannel sc1 = (SocketChannel) key.channel();
								
			StringBuilder sb = new StringBuilder(8192);
			buffer.clear();
			int count = -1;
			while ((count = sc1.read(buffer)) > 0) {
				System.out.println(1);
				buffer.flip();
				while (buffer.hasRemaining()) {
					sb.append((char)buffer.getShort());
				}
				buffer.clear();
			}
			System.out.println(sb.toString());
			key.cancel();
			if(count<0){
				sc1.close();
			}
		}
		it.remove();
	}
}

请问为什么会在sc1.write(buffer)这报报异常



加载中
1
轨迹david
轨迹david
少了  SocketChannel.finishConnect() ,另外, http 1.1貌似需要Host字段,且少了末尾的 \r\n
0
wy65
wy65
要沉了。。。
OSCHINA
登录后可查看更多优质内容
返回顶部
顶部
返回顶部
顶部