问题描述
下面是一个测试例子,主要是连接地址不同,请在注释的地方切换分别测试.希望能详细讲解一下这两个过程,特别是连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.1rnHost: www.baidu.comrnrn".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 OKDate: Fri, 17 Jan 2014 02:39:29 GMTServer: Apache/2.2.25 (Win32)Last-Modified: Sat, 20 Nov 2004 07:16:24 GMTETag: "80c5b3c60-2c-3e94b66a46200"Accept-Ranges: bytesContent-Length: 44Content-Type: text/html<html><body><h1>It works!</h1></body></html>
解决方案
楼主想表达什么意思?第一个连接到百度第二个连接到的是你本机的80.他们输出当然 不一样啊?HTTP协议的话需要指定下HOST就行了,不然默认会按ip解析请求