目录
一、网络编程概述
- Java是 Internet 上的语言,它从语言级上提供了对网络应用程序的支持
- Java提供的网络类库,可以实现无痛的网络连接,联网的底层细节被隐藏在 Java 的本机安装系统里,由 JVM 进行控制
- Java 实现了一个跨平台的网络库,程序员面对的是一个统一 的网络编程环境
- 网络编程的目的:
- 直接或间接地通过网络协议与其它计算机实现数据交换,进行通讯
- 网络编程中有两个主要的问题:
- 如何准确地定位网络上一台或多台主机;定位主机上的特定的应用
- 找到主机后如何可靠高效地进行数据传输
二、网络通信要素概述
- 实现网络中的主机互相通信
- 通信双方地址:
- IP
- 端口号
- 一定的规则:
- OSI参考模型:模型过于理想化,未能在因特网上进行广泛推广
- TCP/IP参考模型(或TCP/IP协议):事实上的国际标准
三、通信要素1:IP和端口号
3.1 IP 地址
- 唯一的标识 Internet 上的计算机(通信实体)
- 本地回环地址(hostAddress):
127.0.0.1
主机名(hostName):localhost
-
- IPV4 :4个字节
- IPV6 :16个字节
-
- 公网地址(万维网使用)
- 私有地址(局域网使用)
3.2 InetAddress类
InetAddress
类:代表一个IP地址,含有一个Internet主机地址的域名 和 IP地址- Internet上的主机有两种方式表示地址:
- 域名(hostName):www.baidu.com
- IP地址(hostAddress):202.108.35.210
- 两个子类:
Inet4Address
、Inet6Address
- 域名解析:当在连接网络时输入一个主机的域名后,域名服务器(DNS)负责将域名转化成IP地址,和主机建立连接
- InetAddress类没有提供公共的构造器,提供了如下几个静态方法来获取InetAddress实例:
public static InetAddress getLocalHost()
public static InetAddress getByName(String host)
- 提供了如下几个常用的方法:
Method | Description |
---|---|
public String getHostAddress() | 返回 IP 地址字符串(以文本表现形式)。 |
public String getHostName() | 获取此 IP 地址的主机名 |
public boolean isReachable(int timeout) | 测试是否可以达到该地址 |
public static void main(String[] args) {
try {
InetAddress inetAddress = InetAddress.getByName("www.baidu.com");
InetAddress inetAddress1 = InetAddress.getByName("127.0.0.1");
//获取本地IP
InetAddress inetAddress2 = InetAddress.getLocalHost();
System.out.println(inetAddress);
System.out.println(inetAddress1);
System.out.println(inetAddress2);
//getHostName
System.out.println(inetAddress1.getHostName());
//getHostAddress
System.out.println(inetAddress1.getHostAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
3.3 端口号
- 端口号:16位的整数 标识正在计算机上运行的进程
- 端口分类:
- 公认端口:0~1023。被预先定义的服务通信占用
如:HTTP占用端口80,FTP占用端口21,Telnet占用端口23 - 注册端口:1024~49151。分配给用户进程或应用程序
如:Tomcat占用端口8080,MySQL占用端口3306,Oracle占用端口1521等 - 动态/私有端口:49152~65535
- 公认端口:0~1023。被预先定义的服务通信占用
四、通信要素2:网络协议
- 网络通信协议:对速率、传输代码、代 码结构、传输控制步骤、出错控制等制定标准
- 通信协议分层的思想:同层间可以通信、上一层可以调用下一层,而与 再下一层不发生关系。各层互不影响,利于系统的开发和扩展
4.1 TCP/IP协议簇
- 传输层协议中有两个非常重要的协议:
- 传输控制协议TCP(Transmission Control Protocol)
- 用户数据报协议UDP(User Datagram Protocol)
- TCP/IP 以其两个主要协议:传输控制协议(TCP)和网络互联协议(IP)而得名,实际上是一组协议,包括多个具有不同功能且互为关联的协议
- IP(Internet Protocol)协议是网络层的主要协议,支持网间互连的数据通信
- TCP/IP协议模型从更实用的角度出发,形成了高效的四层体系结构,即物理链路层、IP层、传输层和应用层
4.2 TCP 和 UDP
- TCP协议:
-
使用TCP协议前,须先建立TCP连接,形成传输数据通道
-
传输前,采用三次握手方式,点对点通信,是可靠的
-
TCP协议进行通信的两个应用进程:客户端、服务端。
-
在连接中可进行大数据量的传输
-
传输完毕,需释放已建立的连接,效率低
-
- UDP协议:
- 将数据、源、目的封装成数据包,不需要建立连接
- 每个数据报的大小限制在64K内
- 发送不管对方是否准备好,接收方收到也不确认,故是不可靠的
- 可以广播发送
- 发送数据结束时无需释放资源,开销小,速度快
五、TCP网络编程
5.1 Socket
- 端口号与IP地址的组合得出一个网络套接字:Socket
- 通信的两端都要有Socket,是两台机器间通信的端点
- 网络通信其实就是Socket间的通信
- Socket允许程序把网络连接当成一个流,数据在两个Socket间通过IO传输
- 一般主动发起通信的应用程序属客户端,等待通信请求的为服务端
- Socket分类:
- 流套接字(stream socket):使用TCP提供可依赖的字节流服务
- 数据报套接字(datagram socket):使用UDP提供“尽力而为”的数据报服务
5.2 Socket类
Socket类的常用构造器:
Method | Description |
---|---|
public Socket(InetAddress address,int port) | 创建一个流套接字并将其连接到指定IP地址的指定端口号 |
public Socket(String host,int port) | 创建一个流套接字并将其连接到指定主机上的指定端口号 |
Socket类的常用方法:
Method | Description |
---|---|
public InputStream getInputStream() | 返回此套接字的输入流。可以用于接收网络消息 |
public OutputStream getOutputStream() | 返回此套接字的输出流。可以用于发送网络消息 |
public InetAddress getInetAddress() | 此套接字连接到的远程 IP 地址;如果套接字是未连接的,则返回 null。 |
public InetAddress getLocalAddress() | 获取套接字绑定的本地地址。 即本端的IP地址 |
public int getPort() | 此套接字连接到的远程端口号;如果尚未连接套接字,则返回 0 |
public int getLocalPort() | 返回此套接字绑定到的本地端口。 如果尚未绑定套接字,则返回 -1。即本端的 端口号 |
public void close() | 关闭此套接字。套接字被关闭后,便不可在以后的网络连接中使用(即无法重新连接 或重新绑定)。需要创建新的套接字对象。 关闭此套接字也将会关闭该套接字的 InputStream 和 OutputStream |
public void shutdownInput() | 如果在套接字上调用 shutdownInput() 后从套接字输入流读取内容,则流将 返回 EOF(文件结束符)。 即不能在从此套接字的输入流中接收任何数据 |
public void shutdownOutput() | 禁用此套接字的输出流。对于 TCP 套接字,任何以前写入的数据都将被发 送,并且后跟 TCP 的正常连接终止序列。 如果在套接字上调用 shutdownOutput() 后写入套接字输出流, 则该流将抛出 IOException。 即不能通过此套接字的输出流发送任何数据 |
5.3 基于Socket的TCP编程
@Test
public void client(){
Socket socket = null;
OutputStream outputStream = null;
FileInputStream fileInputStream = null;
InputStream inputStream = null;
ByteArrayOutputStream byteArrayOutputStream = null;
try {
//1.创建Socket
socket = new Socket(InetAddress.getByName("127.0.0.1"), 9090);
//2.创建Socket的输出流
outputStream = socket.getOutputStream();
//3.获取输入流
fileInputStream = new FileInputStream(new File("IMG_2754.JPG"));
//4.读写数据
byte[] buffer = new byte[1024];
int len;
while ((len=fileInputStream.read(buffer))!=-1){
outputStream.write(buffer,0,len);
}
//关闭数据的输出
socket.shutdownOutput();
//5.接收服务端的反馈
inputStream = socket.getInputStream();
byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer2 = new byte[20];
int len2;
while ((len2=inputStream.read(buffer2))!=-1){
byteArrayOutputStream.write(buffer2,0,len2);
}
System.out.println(byteArrayOutputStream.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
//6.关闭资源
if (fileInputStream!=null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream!=null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket!=null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (byteArrayOutputStream!=null) {
try {
byteArrayOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream!=null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Test
public void server(){
ServerSocket serverSocket = null;
Socket socket = null;
InputStream inputStream = null;
FileOutputStream fileOutputStream = null;
OutputStream outputStream = null;
try {
//1.创建ServerSocket
serverSocket = new ServerSocket(9090);
//2.获取客户端socket
socket = serverSocket.accept();
//3.获取客户端输入流
inputStream = socket.getInputStream();
//4.获取输出流
fileOutputStream = new FileOutputStream(new File("IMG_2754(3).JPG"));
//5.读写过程
byte[] buffer = new byte[1024];
int len;
while ((len=inputStream.read(buffer))!=-1){
fileOutputStream.write(buffer,0,len);
}
System.out.println("图片传输完成");
//6.服务端的反馈
outputStream = socket.getOutputStream();
outputStream.write("已收到客户端的数据".getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
//7.关闭资源
if (fileOutputStream!=null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream!=null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket!=null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (serverSocket!=null) {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream!=null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
5.4 客户端—服务端
- 客户端:
- 自定义
- 浏览器
- 服务端:
- 自定义
- Tomcat服务器
六、UDP网络编程
DatagramSocket
和DatagramPacket
实现了基于 UDP 协议网络程序- UDP数据报通过数据报套接字
DatagramSocket
发送和接收,系统不保证UDP数据报一定能够安全送到目的地,也不能确定什么时候可以抵达(不可靠) DatagramPacket
对象封装了UDP数据报,在数据报中包含了发送端的IP地址和端口号以及接收端的IP地址和端口号- UDP协议中每个数据报都给出了完整的地址信息,因此无须建立发送方和接收方的连接
6.1 DatagramSocket 类的常用方法
Method | Description |
---|---|
public DatagramSocket(int port) | 创建数据报套接字并将其绑定到本地主机上的指定端口。套接字将被绑定到通配符地址,IP 地址由内核来选择。 |
public DatagramSocket(int port,InetAddress laddr) | 创建数据报套接字,将其绑定到指定的本地地址。 本地端口必须在 0 到 65535 之间(包括两者)。如果 IP 地址为 0.0.0.0,套接字将被绑定到通配符地 址,IP 地址由内核选择。 |
public void close() | 关闭此数据报套接字。 |
public void send(DatagramPacket p) | 从此套接字发送数据报包。DatagramPacket 包含的信息指示:将要发送的数据、其长度、远程主机的 IP 地址和远程主机的端口号。 |
public void receive(DatagramPacket p) | 从此套接字接收数据报包。当此方法返回时,DatagramPacket 的缓冲区填充了接收的数据。数据报包也包含发送方的 IP 地址和发送方机器上的端口号。 此方法 在接收到数据报前一直阻塞。数据报包对象的 length 字段包含所接收信息的长度。如果信息比包的 长度长,该信息将被截短。 |
public InetAddress getLocalAddress() | 获取套接字绑定的本地地址。 |
public int getLocalPort() | 返回此套接字绑定的本地主机上的端口号。 |
public InetAddress getInetAddress() | 返回此套接字连接的地址。如果套接字未连接,则返回 null。 |
public int getPort() | 返回此套接字的端口。如果套接字未连接,则返回 -1 |
6.2 DatagramPacket类的常用方法
Method | Description |
---|---|
public DatagramPacket(byte[] buf,int length) | 构造 DatagramPacket,用来接收长度为 length 的数据包。 length 参数必须小于等于 buf.length。 |
public DatagramPacket(byte[] buf,int length,InetAddress address,int port) | 构造数 据报包,用来将长度为 length 的包发送到指定主机上的指定端口号。length 参数必须小于等于 buf.length。 |
public InetAddress getAddress() | 返回某台机器的 IP 地址,此数据报将要发往该机器或者是从该机器接收到的。 |
public int getPort() | 返回某台远程主机的端口号,此数据报将要发往该主机或 者是从该主机接收到的。 |
public byte[] getData() | 返回数据缓冲区。接收到的或将要发送的数据从缓冲区中的偏移量 offset 处开始,持续 length 长度。 |
public int getLength() | 返回将要发送或接收到的数据的长度 |
6.3 UDP网络通信
//发送端
@Test
public void send(){
DatagramSocket socket = null;
try {
socket = new DatagramSocket();
String str = "UTP芜湖";
byte[] data = str.getBytes();
InetAddress inetAddress = InetAddress.getLocalHost();
DatagramPacket packet = new DatagramPacket(data, 0, data.length,inetAddress,9090);
socket.send(packet);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket!=null)
socket.close();
}
}
//接收端
@Test
public void receiver(){
DatagramSocket socket = null;
try {
socket = new DatagramSocket(9090);
byte[] buffer = new byte[100];
DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);
socket.receive(packet);
System.out.println(new String(packet.getData(),0,packet.getLength()));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket!=null)
socket.close();
}
}
七、URL编程
- URL(Uniform Resource Locator):统一资源定位符,表示 Internet 上某一资源的地址
- URL的基本结构由5部分组成:
<传输协议>://<主机名>:<端口号>/<文件名>#片段名?参数列表
例 如 : http://192.168.1.100:8080/helloworld/index.jsp#a?username=shkstart&password=123- #片段名:即锚点,例如看小说,直接定位到章节
- 参数列表格式:参数名=参数值&参数名=参数值…
7.1 URL类
构造器:
Method | Description |
---|---|
public URL (String spec) | 通过一个表示URL地址的字符串可以构造一个URL对象。例 如:URL url = new URL ("http://www. atguigu.com/"); |
public URL(URL context, String spec) | 通过基 URL 和相对 URL 构造一个 URL 对象。例如:URL downloadUrl = new URL(url, “download.html") |
public URL(String protocol, String host, String file) | 例如:new URL("http", "www.atguigu.com", “download. html"); |
public URL(String protocol, String host, int port, String file) | 例如: URL gamelan = new URL("http", "www.atguigu.com", 80, “download.html"); |
一个URL对象生成后,其属性是不能被改变的,但可以通过它给定的 方法来获取这些属性:
Method | Description |
---|---|
public String getProtocol( ) | 获取该URL的协议名 |
public String getHost( ) | 获取该URL的主机名 |
public String getPort( ) | 获取该URL的端口号 |
public String getPath( ) | 获取该URL的文件路径 |
public String getFile( ) | 获取该URL的文件名 |
public String getQuery( ) | 获取该URL的查询名 |
public static void main(String[] args) {
try {
URL url = new URL("https://editor.youkuaiyun.com/md?articleId=105875850");
System.out.println(url.getProtocol());//https
System.out.println(url.getHost());//editor.youkuaiyun.com
System.out.println(url.getPort());//-1
System.out.println(url.getPath());///md
System.out.println(url.getFile());///md?articleId=105875850
System.out.println(url.getQuery());//articleId=105875850
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
7.2 URLConnection类
- URL的方法
openStream()
:能从网络上读取数据 - 若希望输出数据,例如向服务器端的 CGI (公共网关接口-Common Gateway Interface-的简称,是用户浏览器和服务器端的应用程序进行连接的接口)程序发送一 些数据,则必须先与URL建立连接,然后才能对其进行读写,此时需要使用
URLConnection
URLConnection
:表示到URL所引用的远程对象的连接。当与一个URL建立连接时, 首先要在一个 URL 对象上通过方法openConnection()
生成对应的URLConnection
对象。如果连接过程失败,将产生IOException.
- 通过
URLConnection
对象获取的输入流和输出流,即可以与现有的CGI程序进行交互public Object getContent( ) throws IOException
public int getContentLength( )
public String getContentType( )
public long getDate( )
public long getLastModified( )
public InputStream getInputStream( )throws IOException
public OutputSteram getOutputStream( )throws IOException
public static void main(String[] args) {
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
FileOutputStream fileOutputStream = null;
try {
URL url = new URL("http://localhost:8080/examples/myTest.txt");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
inputStream = urlConnection.getInputStream();
fileOutputStream = new FileOutputStream("myTest2.txt");
byte[] buffer = new byte[1024];
int len;
while ((len=inputStream.read(buffer))!=-1){
fileOutputStream.write(buffer,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileOutputStream!=null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream!=null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (urlConnection!=null)
urlConnection.disconnect();
}
}
7.3 URI、URL和URN的区别
URI
:uniform resource identifier,统一资源标识符,用来唯一的标识一个资源URI
是以一种抽象的,高层次概念定义统一资源标识,而URL
和URN
则是具体的资源标识的方式URL
和URN
都是一种URI
URL
:uniform resource locator,统一资源定位符,它是一种具体的URI
,即URL
可以用来标识一个资源,而且还指明了如何locate这个资源URN
:uniform resource name,统一资源命名,是通过名字来标识资源