1.网络编程概述
Java是Internet上的语言,它从语言级上提供了对网络应用程序的支持,程序员能够很容易开发常见的网络应用程序
Java提供的网络类库,可以实现无痛的网络连接,联网的底层细节被隐藏在Java的本机安装系统里,由JVM进行控制。并且Java实现了一个跨平台的网络库,程序员面对的是一个统一的网络编程环境。
计算机网络
把分布在不同地理区域的计算机与专门的外部设备用通信线路互连成一个模大、功能强的网络系统,从而使众多的计算机可以方便地互相传递信息、共享硬件、软件、数据信息等资源。
网络编程的目的:
直接或间接地通过网络协议与其它计算机实现数据交换,进行通讯。
网络编程中有两个主要的问题:
如何准确地定位网络上一台或多台主机:定位主机上的特定的应用
找到主机后如何可靠高效地进行数据传输
2.网络通信要素概述
通信双方的地址:
IP
端口号
一定的规则(即:网络通信协议。有两套参考模型)
OS引参考模型:模型过于理想化,未能在因特网上进行广泛推广
TCP/IP参考模型(或TCP/IP协议):事实上的国际标准
2.1 通信要素一:IP和端口号
IP地址:InetAddress类(在java中使用 InetAddress代表IP)
- 唯一的标识 Internet上的计算机
- 本地回环地址(hostAddress):127.0.0.1 主机名(hostName):localhost
- P地扯分类方式1:IPV4和IPV6
1.IPV4: 4个字节组成,4个0-255。大概42亿,30亿都在北美,亚洲4亿。2011年初已经用尽。以点分十进制表示,如192.168.0.1
2.IPV6:128位(16个字节),写成8个无符号整数,每个整数用四个十六进制位表示,数之间用冒号(:)分开,如:3ffe:3201:1401:1280:c8ff:fe4d:db39:1984- IP地址分类方式2:公网地址(万维网使用)和私有地址(局域网使用)。192.168开头的就是私有址址,范围即为192.168.0.0-192.168.255.255,专门为组织机构内部使用
端口号:
● 端口号标识正在计算机上运行的进程(程序)
- 不同的进程有不同的端口号
- 被规定为一个16位的整数0~65535。
- 端口分类:
1. 公认端口:0~1023。被预先定义的服务通信占用(如:HTTP占用端口
80,FTP占用端口21,Telnet占用端口23)
2. 注册端口:1024~49151。分配给用户进程或应用程序。(如:Tomcat占用端口8080,MySQL占用端口3306,Oracle占用端口1521等)。
3.动态/私有端口:49152~65535。
IP: InetAddress的实例化
(InetAddress.getByName()、InetAddress.getLocalHost)
● 端口号与IP地址的组合得出一个网络套接字:Socket。
public class test_01 {
public static void main(String[] args) {
try {
// ip地址
InetAddress inet1 = InetAddress.getByName("192.168.25.24");
// 域名
InetAddress inet2 = InetAddress.getByName("www.baidu.com"); // 会解析ip地址
// 本地回路地址: 127.0.0.1 (Localhost)
InetAddress inet3 = InetAddress.getByName("Localhost"); // 127.0.0.1
// 直接获取本机地址
InetAddress inet4 = InetAddress.getLocalHost();
System.out.println(inet1);
System.out.println(inet2);
System.out.println(inet3);
System.out.println(inet4);
// 两个常用方法
System.out.println(inet2.getHostName()); // 域名
System.out.println(inet2.getHostAddress()); // ip地址
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
}
}
2.2 通信要素二:网络协议
● 网络通信协议
计算机网络中实现通信必须有一些约定,即通信协议,对速率、传输代码、代码结构、传输控制步骤、出错控制等制定标准。
● 问题:网络协议太复杂
计算机网络通信涉及内容很多,比如指定源地址和目标地址,加密解密,压缩解压缩,差错控制,流量控制,路由控制,如何实现如此复杂的网络协议呢?
●通信协议分层的思想
在制定协议时,把复杂成份分解成一些简单的成份,再将它们复合起来。最常用的复合方式是层次方式,即 同层间可以通信、上一层可以调用下层,而与再下一层不发生关系。各层互不影响,利于系统的开发和扩展。
TCP/IP协议簇:
● 传输层协议中有两个非常重要的协议:
- 传输挖制协议TCP(Transmission Control Protocol)
- 用户数据报协议UDP(User Datagram Protocol)
● TCP/IP以其两个主要协议:传输控制协议(TCP)和网络互联协议(IP) 而得名,实际上是一组协议,包括多个具有不同功能且互为关联的协议。
● lP(Internet Protocol)协议是网络层的主要协议,支持网间互连的数据通信。
● TCPP协议模型从更实用的角度出发,形成了高效的四层体系结构,即
物理链路层、P层、传输层和应用层。
TCP和UDP:
● TCP协议:
- 使用TCP协议前,须先建立TCP连接,形成传输数据通道
- 传输前,采用“三次握手”方式,点对点通信,是可靠的
- TCP协议进行通信的两个应用进程:客户端、服务端。
- 在连接中可进行大数据量的传输
- 传输完毕,需释放已建立的连接,效率低
● UDP协议:
- 将数据、源、目的封装成数据包,不需要建立连接
- 每个数据报的大小限制在64K内
- 发送不管对方是否准备好,接收方收到也不确认,故是不可靠的
- 可以广播发送
- 发送数据结束时无需释放资源,开销小,速度快
TCP生活案例:如打电话
UDP生活案例:发短信、发电报
3.TCP网络编程
1.模拟:客户端口发送信息到服务端口
public class server {
public static void main(String[] args) {
ServerSocket ss = null;
Socket socket = null;
InputStreamReader inputStreamReader = null;
try {
// 1.创建服务器的 ServerSocket,指明当前端口号。(ip不需要指定)
ss = new ServerSocket(8899);
// 2.调用服务器 ServerSocket.accept()方法接受来自客户端的 socket
// (socket相当于一个载体,带着ip和端口号传输数据)
socket = ss.accept();
// 3.从客户端的socket中获取输入流
InputStream inputStream = socket.getInputStream();
inputStreamReader = new InputStreamReader(inputStream);
// 4.读取输入流中的数据
char[] arr = new char[20];
int len;
while((len = inputStreamReader.read(arr)) != -1){
String str = new String(arr,0,len);
System.out.println(str);
}
System.out.println("收到了来自于:"+socket.getInetAddress().getHostName()+"的数据");
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
// 4.资源的关闭
if(inputStreamReader != null){
try {
inputStreamReader.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if(socket != null){
try {
socket.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if(ss != null){
try {
ss.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
}
public class client {
public static void main(String[] args){
Socket socket = null;
OutputStream os = null;
try {
// 1.创建 Socket对象,指明服务器端的ip和端口号
InetAddress inet = InetAddress.getByName("127.0.0.1");
socket = new Socket(inet,8899);
// 2.获取一个输出流,用于输出数据
os = socket.getOutputStream();
// 3.写出数据
os.write("你好!我是客户端!".getBytes());
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if(os != null){
try {
os.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if(socket != null){
try {
socket.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
}
2.模拟:客户端发送到服务端,服务端将文件保存到本地
public class client {
public static void main(String[] args){
Socket socket = null;
OutputStream outputStream = null;
FileInputStream fileInputStream = null;
try {
socket = new Socket(InetAddress.getByName("127.0.0.1"),3456);
outputStream = socket.getOutputStream();
fileInputStream = new FileInputStream("01.jpg");
byte[] arr = new byte[1024];
int len;
while((len = fileInputStream.read(arr)) != -1){
outputStream.write(arr,0,len);
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if(fileInputStream != null){
try {
fileInputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if(outputStream != null){
try {
outputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if(socket != null){
try {
socket.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
}
public class server {
public static void main(String[] args) {
// 服务端
ServerSocket ss = null;
Socket accept = null;
InputStream inputStream = null;
FileOutputStream outputStream = null;
try {
ss = new ServerSocket(3456);
// 接受客户端socket
accept = ss.accept();
inputStream = accept.getInputStream();
// 读取并输出
outputStream = new FileOutputStream("001.jpg");
byte[] arr = new byte[1024];
int len;
while((len = inputStream.read(arr)) != -1){
outputStream.write(arr,0,len);
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if(outputStream != null){
try {
outputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if(inputStream != null){
try {
inputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if(accept != null){
try {
accept.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if(ss != null){
try {
ss.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
}
3.模拟:从客户端发送文件给服务端,服务端保存到本地。并返回“发送成功到客户端”
public class client {
public static void main(String[] args){
Socket socket = null;
OutputStream outputStream = null;
FileInputStream fileInputStream = null;
try {
socket = new Socket(InetAddress.getByName("127.0.0.1"),3456);
outputStream = socket.getOutputStream();
fileInputStream = new FileInputStream("01.jpg");
// 发送给服务器
byte[] arr = new byte[1024];
int len;
while((len = fileInputStream.read(arr)) != -1){
outputStream.write(arr,0,len);
}
// 停止数据的发送
socket.shutdownOutput();
// 得到服务器的反馈
InputStream inputStream = socket.getInputStream();
byte[] arr1 = new byte[1024];
int len1;
while((len = inputStream.read(arr1)) != -1){
System.out.println(new String(arr1,0,len));
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if(fileInputStream != null){
try {
fileInputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if(outputStream != null){
try {
outputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if(socket != null){
try {
socket.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
}
public class server {
public static void main(String[] args) {
// 服务端
ServerSocket ss = null;
Socket accept = null;
InputStream inputStream = null;
FileOutputStream outputStream = null;
try {
ss = new ServerSocket(3456);
// 接受客户端socket
accept = ss.accept();
inputStream = accept.getInputStream();
// 读取并输出
outputStream = new FileOutputStream("002.jpg");
byte[] arr = new byte[1024];
int len;
while((len = inputStream.read(arr)) != -1){
outputStream.write(arr,0,len);
}
// 发送给客户端
OutputStream outputStream1 = accept.getOutputStream();
outputStream1.write("你好!图片已经保存到本地!".getBytes());
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if(outputStream != null){
try {
outputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if(inputStream != null){
try {
inputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if(accept != null){
try {
accept.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if(ss != null){
try {
ss.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
}
4. 模拟:客户端发送英文,经服务器端转换大写后返回给客户端
public class client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),3333);
OutputStream outputStream = socket.getOutputStream();
InputStream inputStream = socket.getInputStream();
String str;
Scanner in = new Scanner(System.in);
System.out.println("请输入要转换大写的英文!");
str = in.nextLine();
outputStream.write(str.getBytes());
socket.shutdownOutput();
byte[] arr = new byte[1024];
int len;
while((len = inputStream.read(arr)) != -1){
str = new String(arr,0,len);
}
System.out.println("转换完成!");
System.out.println(str);
inputStream.close();
outputStream.close();
socket.close();
}
}
public class server {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(3333);
Socket accept = ss.accept();
InputStream inputStream = accept.getInputStream();
OutputStream outputStream = accept.getOutputStream();
String str = null;
byte[] arr = new byte[1024];
int len;
while((len = inputStream.read(arr)) != -1){
str = new String(arr,0,len);
}
String s = str.toUpperCase();
outputStream.write(s.getBytes());
outputStream.close();
inputStream.close();
ss.close();
}
}
4.UDP网络编程
public class send {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket();
String str = "我是udp发送的信息!";
byte[] date = str.getBytes();
InetAddress inet = InetAddress.getLocalHost();
DatagramPacket packet = new DatagramPacket(date,0,date.length,inet,9090);
socket.send(packet);
socket.close();
}
}
public class receiver {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket(9090);
byte[] arr = new byte[100];
DatagramPacket packet = new DatagramPacket(arr,0,arr.length);
socket.receive(packet);
// 获取里面的数据
System.out.println(new String(packet.getData(),0,packet.getLength()));
socket.close();
}
}
5.URL编程
● URL(Uniform Resource Locator): 统一资源定位符,它表示Internet上某一资源的地址。
● 它是一种具体的URl,即URL可以用来标识一个资源,而且还指明了如何locate这个资源。
● 通过URL我们可以访问Internet上的各种网络资源,比如最常见的www,ftp站点。浏览器通过解析给定的URL可以在网络上查找相应的文件或其他资源。
● URL的基本结构由5部分组成:
<传输协议>://<主机名>:<端口号>/<文件名>#片段名?参数列表
例如:http://192.168.1.100:8080/helloworld/index.jsp#ausername=shkstart&password=123
#片段名:即锚点,例如看小说,直接定位到章节
参数列表格式:参数名=参数值&参数名=参数值.…