今天写的一个小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)这报报异常