网络编程
1 网络编程概述
1 概述
- Java是 Internet 上的语言,它从语言级上提供了对网络应用程序的支持,程序员能够很容易开发常见的网络应用程序。
- Java提供的网络类库,可以实现无痛的网络连接,联网的底层细节被隐藏在 Java 的本机安装系统里,由 JVM 进行控制。并且 Java 实现了一个跨平台的网络库, 程序员面对的是一个统一的网络编程环境。
2 计算机网络
-
把分布在不同地理区域的计算机与专门的外部设备用通信线路互连成一个规模大、功能强的网络系统,从而使众多的计算机可以方便地互相传递信息、共享硬件、软件、数据信息等资源。
-
网络编程的目的:直接或间接地通过网络协议与其它计算机实现数据交换,进行通讯。
-
网络编程中有两个主要的问题:
1)如何准确地定位网络上一台或多台主机;定位主机上的特定的应用?==>ip+端口号
2)找到主机后如何可靠高效地进行数据?=>传输协议
3 参考模型
一定的规则(即:网络通信协议。有两套参考模型)
- OSI参考模型:模型过于理想化,未能在因特网上进行广泛推广。
- TCP/IP参考模型(或TCP/IP协议):事实上的国际标准。
4 网络协议
2 网络编程中的两个要素
1 对应问题一:IP和端口号。
1)IP地址(InetAddress)
-
唯一的标识 Internet 上的计算机(通信实体)
-
本地回环地址(hostAddress):127.0.0.1 主机名(hostName):localhost
-
IP地址分类方式1:IPV4 和 IPV6
IPV4:4个字节组成,4个0-255。大概42亿,30亿都在北美,亚洲4亿。2011年初已经用尽。以点分十进制表示,如192.168.0.1
IPV6:128位(16个字节),写成8个无符号整数,每个整数用四个十六进制位表示,数之间用冒号(:)分开,如:3ffe:3201:1401:1280:c8ff:fe4d:db39:1984
-
IP地址分类方式2: 公网地址( 万维网使用)和 私有地址( 局域网使用)。
- 192.168.开头的就是私有址址,范围即为192.168.0.0–192.168.255.255,专门为组织机构内部使用
特点:不易记忆
2)端口号:标识计算机上的运行的进程==>不同的进程存在不同的端口号
①不同的进程有不同的端口号
② 被规定为一个 16 位的整数 0~65535。
③ 端口分类:
- 公认端口:0~1023。被预先定义的服务通信占用(如:HTTP占用端口80,FTP占用端口21,Telnet占用端口23)
- 注册端口:1024~49151。分配给用户进程或应用程序。(如:Tomcat占用端口8080,MySQL占用端口3306,Oracle占用端口1521等)。
- 动态/ 私有端口:49152~65535。
3)IP地址+端口号==网络套接字:Socket
2 对应问题二:提供网络通信协议:TCP/IP参考模型
1) TCP 协议:面向连接的,端对端,可靠的字节流传输协议
- 使用TCP协议前,须先建立TCP连接,形成传输数据通道
- 传输前,采用“ 三次握手”方式,点对点通信,是可靠的
- TCP协议进行通信的两个应用进程:客户端、服务端。
- 在连接中可进行大数据量的传输
- 传输完毕,需释放已建立的连接,效率低
2) UDP 协议:是无需连接的,不可靠的,报文流传输协议。
- 将数据、源、目的封装成数据包,不需要建立连接
- 每个数据报的大小限制在64K内
- 发送不管对方是否准备好,接收方收到也不确认,故是不可靠的
- 可以广播发送
- 发送数据结束时无需释放资源,开销小,速度快
3)三次握手和四次挥手
4)Socket
- 利用套接字(Socket)开发网络应用程序早已被广泛的采用,以至于成为事实上的标准。
- 网络上具有唯一标识的IP地址和端口号组合在一起才能构成唯一能识别的标识符套接字。
- 通信的两端都要有Socket,是两台机器间通信的端点。
- 网络通信其实就是Socket间的通信。
- Socket允许程序把网络连接当成一个流,数据在两个Socket间通过IO传输。
- 一般主动发起通信的应用程序属客户端,等待通信请求的为服务端。
Socket分类:
- 流套接字(stream socket):使用TCP提供可依赖的字节流服务
- 数据报套接字(datagram socket):使用UDP提供“尽力而为”的数据报服务
3 练习
3.1 TCP练习
常见的方法:
- ServerSocket(int port):创建绑定到指定端口的服务器套接字。
- Socket(InetAddress address, int port) :创建流套接字并将其连接到指定IP地址的指定端口号。
- Socket accept() :侦听要连接到此套接字并接受它。
- OutputStream getOutputStream() :返回此套接字的输出流。
- InputStream getInputStream() :返回此套接字的输入流。
- void shutdownInput() :将此套接字的输入流放置在“流的末尾”。
- void shutdownOutput() :禁用此套接字的输出流。
1)InetAddress的简单使用
public class InetAddressTest {
/**
* 实例化InetAddress类
*/
@Test
public void testInetAddress(){
try {
//写法1:ip地址==>"192.168.10.13"
InetAddress inet1 = InetAddress.getByName("192.168.10.13");
///192.168.10.13
System.out.println(inet1);
//写法2:域名==>www.baidu.com
InetAddress baidu = InetAddress.getByName("www.baidu.com");
//www.baidu.com/39.156.66.14
System.out.println(baidu);
//获取本机的ip地址:方式一
InetAddress localHost = InetAddress.getLocalHost();
String hostName = localHost.getHostName();
String hostAddress = localHost.getHostAddress();
//DESKTOP-FGH4UBV/192.168.134.1
System.out.println(localHost);
//DESKTOP-FGH4UBV
System.out.println(hostName);
//192.168.134.1
System.out.println(hostAddress);
//获取本机的ip地址:方式二
InetAddress localHost1 = InetAddress.getByName("127.0.0.1");
///127.0.0.1
System.out.println(localHost1);
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
2)TCP通信协议练习题
package com.atguigu.exer;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.*;
/**
* @author 龍
*/
public class TCPTest1 {
@Test
public void client() {
Socket socket = null;
OutputStream oos = null;
try {
//1.创建Socket对象,指明服务器端的ip和端口号
InetAddress serviceAddress = InetAddress.getByName("192.168.134.1");
socket = new Socket(serviceAddress, 8889);
//2.获取输出流,用于输出数据
oos = socket.getOutputStream();
//3.写出数据
oos.write("你的名字是什么呢?".getBytes());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
//4.关闭资源
if (oos != null) {
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Test
public void server() {
while (true) {
ServerSocket serverSocket = null;
InputStream is = null;
ByteArrayOutputStream baop = null;
Socket accept = null;
try {
//1.创建ServerSocket,指明端口号
serverSocket = new ServerSocket(8889);
//2.调用accept方法,表示接收来自于客户端的socket
accept = serverSocket.accept();
//3.获取一个输入流
is = accept.getInputStream();
/*不建议,可能会出现乱码,建议使用ByteArrayOutputStream
byte[] bytes=new byte[20];
int len=0;
while ((len=is.read(bytes))!=-1){
String string = new String(bytes, 0, len);
System.out.println(string);
}*/
//读取输入流中的数据
baop = new ByteArrayOutputStream();
byte[] buffer = new byte[5];
int len;
while ((len = is.read(buffer)) != -1) {
baop.write(buffer, 0, len);
}
System.out.println("收到了来自于" + accept.getInetAddress().getHostName() + "的消息::" + baop.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (baop != null) {
try {
baop.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (accept != null) {
try {
accept.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
TCP通信协议的练习题2:客户端发送文件到服务器,服务端将文件保存起来。
package com.atguigu.exer;
import org.junit.Test;
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
/**
* 客户端发送文件到服务器,服务端将文件保存起来
*
* @author 龍
*/
public class TCPTest2 {
@Test
public void client() {
Socket socket = null;
OutputStream oos = null;
FileInputStream fis = null;
try {
socket = new Socket(InetAddress.getByName("127.0.0.1"), 8999);
oos = socket.getOutputStream();
fis = new FileInputStream(new File("科比.jpeg"));
byte[] bytes = new byte[1024];
int len;
while ((len = fis.read(bytes)) != -1) {
oos.write(bytes, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (oos != null) {
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Test
public void server() {
ServerSocket serverSocket = null;
Socket socket = null;
InputStream is = null;
FileOutputStream fos = null;
try {
serverSocket = new ServerSocket(8999);
socket = serverSocket.accept();
is = socket.getInputStream();
fos = new FileOutputStream(new File("接收到的文件1.jpeg"));
byte[] bytes = new byte[1024];
int len = 0;
while ((len = is.read(bytes)) != -1) {
fos.write(bytes, 0, len);
}
System.out.println("接收成功");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.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();
}
}
}
}
}
TCP通信协议的练习题3:客户端发送文件到服务器,服务端将文件保存起来,并返回“发送成功”发送给客户端。
package com.atguigu.exer;
import org.junit.Test;
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
/**
* 客户端发送文件给服务器,服务器保存到本地,并返回“发送成功”发送给客户端,
*
* @author 龍
*/
public class TCPTest3 {
@Test
public void client() {
Socket socket = null;
OutputStream oos = null;
FileInputStream fis = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
try {
socket = new Socket(InetAddress.getByName("127.0.0.1"), 8999);
oos = socket.getOutputStream();
fis = new FileInputStream(new File("科比.jpeg"));
byte[] bytes = new byte[1024];
int len;
while ((len = fis.read(bytes)) != -1) {
oos.write(bytes, 0, len);
}
//关闭客户端输出:如果不结束输出的话,服务器会进入阻塞状态,无法停止,告诉服务器端,我发送结束,你可以结束了,然后陷入阻塞状态。
socket.shutdownOutput();
//接收来自服务器的反馈,显示到控制台
is = socket.getInputStream();
baos = new ByteArrayOutputStream();
byte[] bytes1 = new byte[1024];
int len1;
while ((len1 = is.read(bytes1)) != -1) {
baos.write(bytes1, 0, len1);
}
System.out.println(baos.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (baos != null) {
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (oos != null) {
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Test
public void server() {
ServerSocket serverSocket = null;
Socket socket = null;
Socket socket1 = null;
InputStream is = null;
FileOutputStream fos = null;
OutputStream os = null;
try {
serverSocket = new ServerSocket(8999);
socket = serverSocket.accept();
is = socket.getInputStream();
fos = new FileOutputStream(new File("接收到的文件2.jpeg"));
byte[] bytes = new byte[1024];
int len = 0;
while ((len = is.read(bytes)) != -1) {
fos.write(bytes, 0, len);
}
os = socket.getOutputStream();
os.write("发送成功".getBytes());
System.out.println("接收成功");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.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();
}
}
}
}
}
3.2 三次握手,四次挥手
三次握手:
四次挥手:
4 UDP网络编程流程
- DatagramSocket与DatagramPacket
- 建立发送端,接收端
- 建立数据包
- 调用Socket的发送、接收方法
- 关闭Socket
- 发送端与接收端是两个独立的运行程序
常见方法:
- DatagramPacket(byte[] buf, int length) :构造一个 DatagramPacket用于接收长度的数据包 length 。
- DatagramPacket(byte[] buf, int length, InetAddress address, int port)
构造用于发送长度的分组的数据报包 length指定主机上到指定的端口号。 - DatagramPacket(byte[] buf, int offset, int length) :构造一个DatagramPacket用于接收长度的分组 length ,指定偏移到缓冲器中。
- DatagramPacket(byte[] buf, int offset, int length, InetAddress address, int port) :构造用于发送长度的分组数据报包 length具有偏移 ioffset指定主机上到指定的端口号。
- DatagramPacket(byte[] buf, int offset, int length, SocketAddress address) :构造用于发送长度的分组数据报包 length具有偏移 ioffset指定主机上到指定的端口号。
- DatagramPacket(byte[] buf, int length, SocketAddress address) :构造用于发送长度的分组的数据报包 length指定主机上到指定的端口号。
package com.atguigu.exer1;
import org.junit.Test;
import java.io.IOException;
import java.net.*;
/**
* UDP协议的网络编程
* 直接启动客户端发现不会报错。而TCP会报错。
* @author 龍
*/
public class UDPTest {
@Test
public void sender(){
DatagramSocket socket =null;
DatagramPacket packet =null;
try {
//1.创建DatagramSocket对象
socket = new DatagramSocket();
//2.创建传送的数据
String str="UDP协议的网络测试";
byte[] data = str.getBytes();
//3.获取发送地址
InetAddress localHost = InetAddress.getLocalHost();
//4.数据封装到packet中
packet = new DatagramPacket(data,0,data.length,localHost,9090);
//5.发送数据
socket.send(packet);
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (socket!=null){
socket.close();
}
}
}
@Test
public void receiver(){
DatagramSocket socket =null;
DatagramPacket packet =null;
try {
//1.创建DatagramSocket对象
socket = new DatagramSocket(9090);
//2.创建准备接收数据的数据包
byte[] bytes=new byte[1024];
packet = new DatagramPacket(bytes,0,bytes.length);
//3.接收数据包
socket.receive(packet);
//4.读取数据包
byte[] data = packet.getData();
System.out.println(new String(packet.getData(), 0, packet.getLength()));
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (socket!=null){
socket.close();
}
}
}
}
5 URL编程
URL类
-
URL(Uniform Resource Locator):统一资源定位符,它表示 Internet上某一资源的地址。
-
它是一种具体的URI,即URL可以用来标识一个资源,而且还指明了如何locate这个资源。
-
通过 URL 我们可以访问 Internet 上的各种网络资源,比如最常见的 www,ftp站点。浏览器通过解析给定的 URL 可以在网络上查找相应的文件或其他资源。
-
URL的基本结构由5部分组成:
< 传输协议>://< 主机名>:< 端口号>/< 文件名># 片段名? 参数列表
例如:
http://192.168.1.100:8080/helloworld/index.jsp#a?username=shkstart&password=123
- #片段名:即锚点,例如看小说,直接定位到章节
- 参数列表格式:参数名=参数值&参数名=参数值…
package com.atguigu.exer2;
import org.junit.Test;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.*;
/**
* 根据url下载资源
*
* @author 龍
*/
public class URLTested {
@Test
public void testURL() {
HttpURLConnection urlConnection = null;
InputStream is = null;
FileOutputStream fos = null;
try {
//1.实例化URl,填入URL链接
URL url = new URL("http://localhost/example/kebo.jpeg");
//2.获取HttpURLConnection对象
urlConnection = (HttpURLConnection) url.openConnection();
//3.获取连接
urlConnection.getContent();
//4.读取数据并下载到本地
is = urlConnection.getInputStream();
fos = new FileOutputStream(new File("URL_kebo.jpeg"));
byte[] bytes = new byte[1024];
int len;
while ((len = is.read(bytes)) != -1) {
fos.write(bytes, 0, len);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
//5.关闭流和连接
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (urlConnection != null) {
urlConnection.disconnect();
}
}
}
}
每日一考
1.一个Ip对应着哪个类的一个对象?InetAddress
实例化对象:
InetAddress.getByName(String host); //获取指定的ip
InetAddress.getLocalHost();//获取本地ip
常用的方法:
getHostName();
getHostAddress();
2.传输层TCP和UDP协议的主要区别是?
TCP:可靠的数据传输(三次握手),先进行连接然后再进行数据传输,连接之后可以进行大数据量的传输。效率相对比较低。
UDP:不可靠,提供尽最大努力交付的服务。以数据包为单位进行传输,大小被限制为64kb大小。效率比较高。
3.什么url,你能写出一个URL吗
URL:统一资源定位符。
URL url=new URL(“http://192.168.40.1:8080/example/kebo.jpeg?username=Toms”)。
4.谈谈你对对象序列化机制的理解
序列化:将对象转化为二进制数据保存到硬盘中。
反序列化:将硬盘中的二进制数据转化为对象。
5.对象想要序列化需要满足什么条件
>实现Serializable接口
>指定一个private static final long seriaVersionUID=
>对象的属性是可序列化的,基本数据类型都是可以序列化的。
属性不能用transient和static来进行修饰,该属性值序列化和反序列化之后是无法保存下来的。