1、网络:把分布在不同地理区域的计算机与专门的外部设备用通信线路互连成一个规模大、功能强的网络系统。
计算机网络提供了资源共享、信息传输与集中处理、均衡负荷与分布处理以及综合信息服务等丰富的功能。
通信协议:通过它对速率、传输代码、代码结构、传输控制步骤、出错控制等制定标准。
计算机网络协议通常由3部分组成:1)语义部分,对话的类型
2)语法部分,对话的格式
3)变换规则,应答关系
国际标准化组织(ISO)与1978年提出了“开放系统互连参考模型”,即著名的OSI(Open System Interconnection)模型。开放系统互连参考模型把计算机网路分成物理层、数据链路层、网络层、传输层、会话层、表示层、应用层等7层。
2、TCP/IP协议是当今网络传输的基本协议。IP协议可以进行IP数据包的分割和组装,而TCP协议将数据包装成功发送给目标计算机后,会请求对方返回一个确认。
TCP协议提供可靠的数据传输服务规则。
IP协议规定了Internet数据传输的基本单元和格式,同时,还定义了数据的路由选择。
3、IP地址和端口号
IP地址:网络中的每台机器都必须有一个与众不同的标识。
Ip地址的格式为:数字型、32位、由4段8位的二进制数组成。一般表示为十进制形式(4个0~255的十进制整数),中间用电隔开。
端口:是由一个16位的整数,用于表示数据交给那个通信程序处理。
端口就是应用程序与外界交流的入口,它是一种抽象的软件结构,包括一些数据的结构的I/O缓冲区。
端口号可以从0~65535,通常分为3类:
公认端口(0~1023)、注册端口(1024~49151)、动态和/或私有端口(49152~65535)
4、InetAddress类的使用
java.net.InetAddress类的主要作用是IP地址。
InetAddress类没有提供构造方法,而是提供了两个静态方法来获取InetAddress实例。
例:
import java.net.*;
public class TestNet1{
public static void main(String[] args)throws Exception{
InetAddress ip=InetAddress.getByName("www.oneedu.cn");
System.out.println("oneedu 是否可到达:"+ip.isReachable(2000));
System.out.println(ip.getHostAddress());
InetAddress local=InetAddress.getByAddress(new byte[]{127.0.0.1});
System.out.println("本机是否可到达:"+ip.isReachable(5000));
System.out.println(local.getCanonicalHostName());
}
}
5、URL类的使用
URL类代表统一资源定位器,统一资源定位器是指互联网“资源”的名称。
通常URL可以由协议名、主机、端口和资源组成。URL的格式为“protocol://host:port/resourceName"
常用的两个构造方法,用于创建URL对象:public URL(String str)
public URL(URL context,String str)
例:
import java.net.URL;
import java.io.*;
public class TestNet2{
public static void main(String[] args)throws Exception{
URL aURL=new URL("http://java.sun.com:80/docs/books/tutorial"+"/index.html?name=networking#DOWNLOADING");
System.out.println("protocol="+aURL.getProtocol());
System.out.println("authority="+aURL.getAuthority());
System.out.println("host="+aURL.getHost());
System.out.println("port="+aURL.getPort());
System.out.println("path="+aURL.getPath());
System.out.println("query="+aURL.getQuery());
System.out.println("filename="+aURL.getFile());
System.out.println("ref="+aURL.getRef());
}
}
package com;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.net.URL;
public class TestNet3{
public static void main(String[] args)throws Exception{
URL url=new URL("http://localhost:8080");
InputStreamReader isr=new InputStreamReader(url.openStream());
BufferedReader in=new BufferedReader(isr);
String inputLine;
FileOutputStream fos=new FileOutputStream("d://mydownloadhtml.htmil");
while((inputLine=in.readLine())!=null){
fos.write(inputLine.getBytes());
//System.out.println(inputLine);//显示到控制台
}
in.close();
}
}