下面是一个测试例子,主要是连接地址不同,请在注释的地方切换分别测试.希望能详细讲解一下这两个过程,特别是连127.0.0.1这个
1) InetSocketAddress addr = new InetSocketAddress("www.baidu.com", 80);
2) //InetSocketAddress addr = new InetSocketAddress("127.0.0.1", 80);
/**
- NIO_baidu.java
- Version 1.0
- 2014-1-16
- Copyright www.wangjiu.com */ package com._0116;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
/**
- TODO (描述类的功能)
- @author d
-
2014-1-16
*
*/
public class NIO_baidu {/**
- TODO (描述方法的作用)
- @param args
-
@throws Exception
*/
public static void main(String[] args) throws Exception {
// 用下面两个连接地址分别测试
InetSocketAddress addr = new InetSocketAddress("www.baidu.com", 80);
//InetSocketAddress addr = new InetSocketAddress("127.0.0.1", 80);
SocketChannel channel = SocketChannel.open(addr);System.out.println();
byte[] header = "GET / HTTP/1.1\r\nHost: www.baidu.com\r\n\r\n".getBytes();
ByteBuffer buf = ByteBuffer.allocate(header.length);
buf.put(header);
buf.flip();
channel.write(buf);buf = ByteBuffer.allocate(1024);
int count = channel.read(buf);
while(count != -1) {
buf.flip();
while(buf.hasRemaining()){
System.out.print((char)buf.get());
}
buf.clear();
count = channel.read(buf);
System.out.print(count);
}
channel.close();
}
}
第一个的返回结果是:
就是百度首页的html代码,太长了贴不下.
第二个返回结果是:
HTTP/1.1 200 OK
Date: Fri, 17 Jan 2014 02:39:29 GMT
Server: Apache/2.2.25 (Win32)
Last-Modified: Sat, 20 Nov 2004 07:16:24 GMT
ETag: "80c5b3c60-2c-3e94b66a46200"
Accept-Ranges: bytes
Content-Length: 44
Content-Type: text/html