欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

Java网络编程

时间:2023-06-12
1.网络编程概述

Java是 Internet 上的语言,它从语言级上提供了对网络应用程 序的支持,程序员能够很容易开发常见的网络应用程序。Java提供的网络类库,可以实现无痛的网络连接,联网的底层细节被隐藏在 Java 的本机安装系统里,由 JVM 进行控制。并 且 Java 实现了一个跨平台的网络库,程序员面对的是一个统一 的网络编程环境。

计算机网络:

把分布在不同地理区域的计算机与专门的外部设备用通信线路互连成一个规 模大、功能强的网络系统,从而使众多的计算机可以方便地互相传递信息、 共享硬件、软件、数据信息等资源。

网络编程的目的:

直接或间接地通过网络协议与其它计算机实现数据交换,进行通讯。

网络编程中有两个主要的问题:

如何准确地定位网络上一台或多台主机;定位主机上的特定的应用

找到主机后如何可靠高效地进行数据传输

2.网络通信要素概述 2.1通信双方地址

 IP

 端口号

2.2一定的规则

 OSI参考模型:模型过于理想化,未能在因特网上进行广泛推广

 TCP/IP参考模型(或TCP/IP协议):事实上的国际标准。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-zge8JNy3-1644756386511)(C:UserslinyinleiAppDataRoamingTyporatypora-user-imagesimage-20220213125058742.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-aREx4jjQ-1644756386512)(C:UserslinyinleiAppDataRoamingTyporatypora-user-imagesimage-20220213125122797.png)]

3.通信要素1:IP和端口号 3.1 IP

唯一的标识 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,专门为组织机 构内部使用

特点:不易记忆

3.2端口号

标识正在计算机上运行的进程(程序)

 不同的进程有不同的端口号

 被规定为一个 16 位的整数 0~65535。

 端口分类:

​  公认端口:0~1023。被预先定义的服务通信占用(如:HTTP占用端口 80,FTP占用端口21,Telnet占用端口23)

​  注册端口:1024~49151。分配给用户进程或应用程序。(如:Tomcat占 用端口8080,MySQL占用端口3306,Oracle占用端口1521等)。

​  动态/私有端口:49152~65535。

端口号与IP地址的组合得出一个网络套接字:Socket。 3.3 InetAddress类

Internet上的主机有两种方式表示地址:

域名(hostName):www.atguigu.com

IP 地址(hostAddress):202.108.35.210

InetAddress类主要表示IP地址,两个子类:Inet4Address、Inet6Address。

InetAddress 类 对 象 含 有 一 个 Internet 主 机 地 址 的 域 名 和 IP 地 址 : www.atguigu.com 和 202.108.35.210。

域名容易记忆,当在连接网络时输入一个主机的域名后,域名服务器(DNS) 负责将域名转化成IP地址,这样才能和主机建立连接。 -------域名解析

InetAddress类没有提供公共的构造器,而是提供了如下几个静态方法来获取 InetAddress实例

​ public static InetAddress getLocalHost()

​ public static InetAddress getByName(String host)

InetAddress提供了如下几个常用的方法

​ public String getHostAddress():返回 IP 地址字符串(以文本表现形式)。

​ public String getHostName():获取此 IP 地址的主机名

​ public boolean isReachable(int timeout):测试是否可以达到该地址

public class InetAddressTest { public static void main(String[] args) { try { InetAddress inet1 = InetAddress.getByName("192.168.1.10"); System.out.println(inet1); InetAddress inet2 = InetAddress.getByName("www.atguigu.com"); System.out.println(inet2); InetAddress inet3 = InetAddress.getByName("127.0.0.1"); System.out.println(inet3); //获取本地ip InetAddress inet4 = InetAddress.getLocalHost(); System.out.println(inet4); //getHostName() System.out.println(inet2.getHostName()); //getHostAddress() System.out.println(inet2.getHostAddress()); Boolean flag = inet1.isReachable(25); System.out.println(flag); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }}

4.通信要素2:网络协议

网络通信协议

计算机网络中实现通信必须有一些约定,即通信协议,对速率、传输代码、代 码结构、传输控制步骤、出错控制等制定标准。

问题:网络协议太复杂

计算机网络通信涉及内容很多,比如指定源地址和目标地址,加密解密,压缩 解压缩,差错控制,流量控制,路由控制,如何实现如此复杂的网络协议呢?

通信协议分层的思想

在制定协议时,把复杂成份分解成一些简单的成份,再将它们复合起来。最常 用的复合方式是层次方式,即同层间可以通信、上一层可以调用下一层,而与 再下一层不发生关系。各层互不影响,利于系统的开发和扩展。

TCP/IP协议簇

传输层协议中有两个非常重要的协议:

​  传输控制协议TCP(Transmission Control Protocol)

​  用户数据报协议UDP(User Datagram Protocol)

TCP/IP 以其两个主要协议:传输控制协议(TCP)和网络互联协议(IP)而得 名,实际上是一组协议,包括多个具有不同功能且互为关联的协议。

IP(Internet Protocol)协议是网络层的主要协议,支持网间互连的数据通信。

TCP/IP协议模型从更实用的角度出发,形成了高效的四层体系结构,即 物理链路层、IP层、传输层和应用层。

TCP 和 UDP

TCP协议:

 使用TCP协议前,须先建立TCP连接,形成传输数据通道

 传输前,采用“三次握手”方式,点对点通信,是可靠的

 TCP协议进行通信的两个应用进程:客户端、服务端。

 在连接中可进行大数据量的传输  传输完毕,需释放已建立的连接,效率低

UDP协议:

 将数据、源、目的封装成数据包,不需要建立连接

 每个数据报的大小限制在64K内

 发送不管对方是否准备好,接收方收到也不确认,故是不可靠的

 可以广播发送

 发送数据结束时无需释放资源,开销小,速度快

Socket

 利用套接字(Socket)开发网络应用程序早已被广泛的采用,以至于成为事实 上的标准。

 网络上具有唯一标识的IP地址和端口号组合在一起才能构成唯一能识别的标 识符套接字。

 通信的两端都要有Socket,是两台机器间通信的端点。

 网络通信其实就是Socket间的通信。

 Socket允许程序把网络连接当成一个流,数据在两个Socket间通过IO传输。

 一般主动发起通信的应用程序属客户端,等待通信请求的为服务端。 Socket分类:

​ 流套接字(stream socket):使用TCP提供可依赖的字节流服务

​ 数据报套接字(datagram socket):使用UDP提供“尽力而为”的数据报服务

5.TCP网络编程

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-tUSGFqjR-1644756386513)(C:UserslinyinleiAppDataRoamingTyporatypora-user-imagesimage-20220213140516795.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-OVr6kr10-1644756386513)(C:UserslinyinleiAppDataRoamingTyporatypora-user-imagesimage-20220213143744986.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-XebxZaYU-1644756386513)(C:UserslinyinleiAppDataRoamingTyporatypora-user-imagesimage-20220213144012320.png)]

6.练习

1.客户端发送内容给服务端,服务端将内容打印到控制台上。

public class TCPTest1 { //客户端 @Test public void client() { Socket socket = null; OutputStream os = null; try { //1.创建Socket对象,指明服务器端的ip和端口号 InetAddress inet = InetAddress.getByName("192.168.1.10"); socket = new Socket(inet,8899); //2.获取一个输出流,用于输出数据 os = socket.getOutputStream(); //3.写出数据的操作 os.write("你好,我是客户端mm".getBytes()); } catch (IOException e) { e.printStackTrace(); } finally { //4.资源的关闭 if(os != null){ try { os.close(); } catch (IOException e) { e.printStackTrace(); } } if(socket != null){ try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } } //服务端 @Test public void server() { ServerSocket ss = null; Socket socket = null; InputStream is = null; ByteArrayOutputStream baos = null; try { //1.创建服务器端的ServerSocket,指明自己的端口号 ss = new ServerSocket(8899); //2.调用accept()表示接收来自于客户端的socket socket = ss.accept(); //3.获取输入流 is = socket.getInputStream(); //不建议这样写,中文的字节流转换可能会有乱码// byte[] buffer = new byte[1024];// int len;// while((len = is.read(buffer)) != -1){// String str = new String(buffer,0,len);// System.out.print(str);// } //4.读取输入流中的数据 baos = new ByteArrayOutputStream(); byte[] buffer = new byte[5]; int len; while((len = is.read(buffer)) != -1){ baos.write(buffer,0,len); } System.out.println(baos.toString()); System.out.println("收到了来自于:" + socket.getInetAddress().getHostAddress() + "的数据"); } catch (IOException e) { e.printStackTrace(); } finally { if(baos != null){ //5.关闭资源 try { baos.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(ss != null){ try { ss.close(); } catch (IOException e) { e.printStackTrace(); } } } }}

2.客户端发送文件给服务端,服务端将文件保存在本地。

public class TCPTest2 { @Test public void client() { Socket socket = null; OutputStream os = null; FileInputStream fis = null; try { //1. socket = new Socket(InetAddress.getByName("127.0.0.1"),9090); //2. os = socket.getOutputStream(); //3. fis = new FileInputStream(new File("beauty.jpg")); //4. byte[] buffer = new byte[1024]; int len; while((len = fis.read(buffer)) != -1){ os.write(buffer,0,len); } } catch (IOException e) { e.printStackTrace(); } finally { //5. if(fis != null){ try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } if(os != null){ try { os.close(); } catch (IOException e) { e.printStackTrace(); } } if(socket != null){ try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } } @Test public void server() { ServerSocket ss = null; Socket socket = null; InputStream is = null; FileOutputStream fos = null; try { //1. ss = new ServerSocket(9090); //2. socket = ss.accept(); //3. is = socket.getInputStream(); //4. fos = new FileOutputStream(new File("beauty1.jpg")); //5. byte[] buffer = new byte[1024]; int len; while((len = is.read(buffer)) != -1){ fos.write(buffer,0,len); } //6. } 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(ss != null){ try { ss.close(); } catch (IOException e) { e.printStackTrace(); } } } }}

3.从客户端发送文件给服务端,服务端保存到本地。并返回“发送成功”给 客户端。并关闭相应的连接。

public class TCPTest3 { @Test public void client() { Socket socket = null; OutputStream os = null; FileInputStream fis = null; ByteArrayOutputStream baos = null; try { //1. socket = new Socket(InetAddress.getByName("127.0.0.1"),9090); //2. os = socket.getOutputStream(); //3. fis = new FileInputStream(new File("beauty.jpg")); //4. byte[] buffer = new byte[1024]; int len; while((len = fis.read(buffer)) != -1){ os.write(buffer,0,len); } //关闭数据的输出 socket.shutdownOutput(); //5.接收来自于服务器端的数据,并显示到控制台上 InputStream is = socket.getInputStream(); baos = new ByteArrayOutputStream(); byte[] bufferr = new byte[20]; int len1; while((len1 = is.read(buffer)) != -1){ baos.write(buffer,0,len1); } System.out.println(baos.toString()); } catch (IOException e) { e.printStackTrace(); } finally { //6. if(fis != null){ try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } if(os != null){ try { os.close(); } catch (IOException e) { e.printStackTrace(); } } if(socket != null){ try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } if(baos != null){ try { baos.close(); } catch (IOException e) { e.printStackTrace(); } } } } @Test public void server() { ServerSocket ss = null; Socket socket = null; InputStream is = null; FileOutputStream fos = null; OutputStream os = null; try { //1. ss = new ServerSocket(9090); //2. socket = ss.accept(); //3. is = socket.getInputStream(); //4. fos = new FileOutputStream(new File("beauty2.jpg")); //5. byte[] buffer = new byte[1024]; int len; while((len = is.read(buffer)) != -1){ fos.write(buffer,0,len); } System.out.println("图片传输完成"); //6.服务器端给予客户端反馈 os = socket.getOutputStream(); os.write("你好,美女,照片我已收到,非常漂亮!".getBytes()); } catch (IOException e) { e.printStackTrace(); } finally { //7. 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(ss != null){ try { ss.close(); } catch (IOException e) { e.printStackTrace(); } } if(os != null){ try { os.close(); } catch (IOException e) { e.printStackTrace(); } } } }}

7.UDP网络编程

 类 DatagramSocket 和 DatagramPacket 实现了基于 UDP 协议网络程序。

 UDP数据报通过数据报套接字 DatagramSocket 发送和接收,系统不保证 UDP数据报一定能够安全送到目的地,也不能确定什么时候可以抵达。

 DatagramPacket 对象封装了UDP数据报,在数据报中包含了发送端的IP 地址和端口号以及接收端的IP地址和端口号。

 UDP协议中每个数据报都给出了完整的地址信息,因此无须建立发送方和 接收方的连接。如同发快递包裹一样。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-RetWigSE-1644756386514)(C:UserslinyinleiAppDataRoamingTyporatypora-user-imagesimage-20220213165301324.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-nyTgIA4L-1644756386514)(C:UserslinyinleiAppDataRoamingTyporatypora-user-imagesimage-20220213165315188.png)]

public class UDPTest { //发送端 @Test public void sender() { DatagramSocket socket = null; try { socket = new DatagramSocket(); String str = "我是UDP方式发送的导弹"; byte[] data = str.getBytes(); InetAddress inet = InetAddress.getLocalHost(); DatagramPacket packet = new DatagramPacket(data,0,data.length,inet,9090); socket.send(packet); } catch (IOException e) { e.printStackTrace(); } finally { if(socket != null){ socket.close(); } } } //接收端 @Test public void receiver() throws IOException { 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(); } } }}

8.URL编程

URL:统一资源定位符,它表示 Internet 上某一 资源的地址。通过 URL 我们可以访问 Internet 上的各种网络资源,浏览器通过解析给定的 URL 可以在网络上查找相应的文件或其他资源。

URL的基本结构由5部分组成:

<传输协议>://<主机名>:<端口号>/<文件名>#片段名?参数列表

类 URL

​ 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类的构造器都声明抛出非运行时异常,必须要对这一异常进行处理,通 常是用 try-catch 语句进行捕获

public class URLTest { public static void main(String[] args) { try { URL url = new URL("http://localhost:8080/examples/beauty.jpg?username=Tom");// public String getProtocol( ) 获取该URL的协议名 System.out.println(url.getProtocol());// public String getHost( ) 获取该URL的主机名 System.out.println(url.getHost());// public String getPort( ) 获取该URL的端口号 System.out.println(url.getPort());// public String getPath( ) 获取该URL的文件路径 System.out.println(url.getPath());// public String getFile( ) 获取该URL的文件名 System.out.println(url.getFile());// public String getQuery( ) 获取该URL的查询名 System.out.println(url.getQuery()); } catch (MalformedURLException e) { e.printStackTrace(); } }}//结果为:http localhost 8080 /examples/beauty.jpg/examples/beauty.jpg?username=Tomusername=Tom

针对HTTP协议的URLConnection类

若希望输出数据,例如向服务器端的 CGI (公共网关接口-Common Gateway Interface-的简称,是用户浏览器和服务器端的应用程序进行连接的接口)程序发送一 些数据,则必须先与URL建立连接,然后才能对其进行读写,此时需要使用 URLConnection 。

URLConnection:表示到URL所引用的远程对象的连接。当与一个URL建立连接时, 首先要在一个 URL 对象上通过方法 openConnection() 生成对应的 URLConnection 对象。如果连接过程失败,将产生IOException

​ URL netchinaren = new URL (“http://www.atguigu.com/index.shtml”);

​ URLConnectonn u = netchinaren.openConnection( );

通过URLConnection对象获取的输入流和输出流,即可以与现有的CGI 程序进行交互。

public InputStream getInputStream( )throws IOException

public OutputSteram getOutputStream( )throws IOException

public class URLTest1 { public static void main(String[] args) { HttpURLConnection urlConnection = null; InputStream is = null; FileOutputStream fos = null; try { URL url = new URL("https://cn.bing.com/images/search?view=detailV2&ccid=gyU79QB8&id=F2F764F135DB03E3712B9566371AFAE4D4F83148&thid=OIP.gyU79QB8088FwxWo89CCCwHaEy&mediaurl=https%3a%2f%2ftse1-mm.cn.bing.net%2fth%2fid%2fR-C.83253bf5007cd3cf05c315a8f3d0820b%3frik%3dSDH41OT6GjdmlQ%26riu%3dhttp%253a%252f%252fwww.desktx.com%252fd%252ffile%252fwallpaper%252fscenery%252f20170215%252ff2d0a76c4d45e7255022f3c511e8bd7a.jpg%26ehk%3dSt4XCEEUbOi7HWL7L77WZEyZp096qDgXF070s0sw3Lg%253d%26risl%3d%26pid%3dImgRaw%26r%3d0&exph=1119&expw=1730&q=%e5%9b%be%e7%89%87&simid=607995119668648231&FORM=IRPRST&ck=7785C0AF98B498E750DF60C6C7C6A264&selectedIndex=0&idpp=overlayview&ajaxhist=0&ajaxserp=0"); urlConnection = (HttpURLConnection)url.openConnection(); urlConnection.connect(); is = urlConnection.getInputStream(); fos = new FileOutputStream("day05\beauty4.jpg"); byte[] buffer = new byte[1024]; int len; while((len = is.read(buffer)) != -1){ fos.write(buffer,0,len); } System.out.println("下载完成"); } catch (IOException e) { e.printStackTrace(); } finally { //关闭资源 if(is != null){ try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if(fos != null){ try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } if(urlConnection != null){ urlConnection.disconnect(); } } }}

9.URI、URL和URN的区别

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-wh1MU853-1644756386515)(C:UserslinyinleiAppDataRoamingTyporatypora-user-imagesimage-20220213203800842.png)]

10.小结

fos.write(buffer,0,len); } System.out.println("下载完成"); } catch (IOException e) { e.printStackTrace(); } finally { //关闭资源 if(is != null){ try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if(fos != null){ try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } if(urlConnection != null){ urlConnection.disconnect(); } }}

}

### 9.URI、URL和URN的区别[外链图片转存中...(img-wh1MU853-1644756386515)]### 10.小结[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-DMOQni5w-1644756386515)(C:UserslinyinleiAppDataRoamingTyporatypora-user-imagesimage-20220213203926593.png)]

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。