Baozi series -- Java basics Chapter 14_ Network programming

baozi series java basics chapter


Chapter 14 Network programming

image-20201111202804994.png

InetAddress class

Two problems need to be solved to realize network communication

  1. How to accurately locate one or more hosts on the network ; Locate specific applications on the host
  2. How to transfer data reliably and efficiently after finding the host

Two elements of network communication

  1. Corresponding to question 1 :IP And port number
  2. Corresponding to question 2 : Provide network communication protocol :TCP/IP Reference model ( application layer 、 Transport layer 、 The network layer 、 Physics + Data link layer )

Communication element 1 :IP And port number

IP The understanding of the

  1. IP: The only sign Internet Computers on ( Communication entities )
  2. stay Java Use in InetAddress Class representative IP
  3. IP classification :IPv4 and IPv6 ; web and LAN
  4. domain name : www.baidu.com www.mi.com www.sina.com www.jd.com
  5. Local loop address :127.0.0.1 Corresponding :localhost

Domain name resolution : Domain names are easy to remember , When connecting to the network, enter the domain name of a host , Domain name server (DNS) Responsible for translating domain names into IP Address , In this way, we can establish a connection with the host . ------- Domain name resolution

Port number and IP The combination of addresses leads to a network socket :Socket.

InetAddress class : An object of this class represents a specific IP Address

Internet There are two ways for a host on to represent an address :

  • domain name (hostName):www.atguigu.com
  • IP Address (hostAddress):202.108.35.210

InetAddress Class mainly represents IP Address , Two subclasses :Inet4Address、Inet6Address.

InetAddress class Yes like contain Yes One individual Internet Lord machine The earth site Of Domain name and IP The earth site : www.atguigu.com and 202.108.35.210.

Instantiation

netAddress Class does not provide a public constructor , Instead, it provides the following static methods to get InetAddress example

getByName(String host) 、 getLocalHost()
public static InetAddress getLocalHost()
public static InetAddress getByName(String host)

Common methods

getHostName() / getHostAddress()
public String getHostAddress(): return IP Address string ( In the form of text ).
public String getHostName(): Access to this IP The host name of the address

Example

image-20201111193816114.png

Port number

A process that is running on a computer

  • requirement : Different processes have different port numbers
  • Range : To be defined as a 16 An integer 0~65535.
  • Port number and IP The combination of addresses leads to a network socket :Socket

Communication element 2 : Network communication protocol

Classification model

image-20201111193924155.png

TCP and UDP The difference between

image-20201111193935618.png

TCP Three handshakes and four waves

image-20201111194012602.png

image-20201111194102042.png

Socket classification

  • Stream Socket (stream socket): Use TCP Provide reliable byte stream Services
  • Socket datagram (datagram socket): Use UDP Provide “ Do my best ” Datagram service for

TCP Network programming

be based on Socket Of TCP Programming

image-20201111194439483.png

client Socket There are four basic steps in the process :

  • establish Socket: According to the specified server IP Address or port number construction Socket Class object . If the server side Respond to , Then establish the communication line from the client to the server . If the connection fails , There will be anomalies .
  • Open the connection to Socket The input of / Outflow : Use getInputStream() Method to get the input stream , Use getOutputStream() Method to get the output stream , Data transfer
  • According to a certain agreement Socket Read / Write operations : Read the information that the server put into the line through the input stream ( But I can't read the information I put in the line ), Write information to the thread through the output stream .
  • close Socket: Disconnect the client from the server , Release the line

The working process of the server program includes the following four basic steps

  • call ServerSocket(int port) : Create a server socket , And bind to the specified port On . Used to listen for requests from clients
  • call accept(): Listen for connection requests , If the client requests a connection , Then accept the connection , Back to communication Socket object
  • call The Socket Class object getOutputStream() and getInputStream (): Get output Streams and input streams , Start sending and receiving network data .
  • close ServerSocket and Socket object : End of client access , Close communication socket .

Code example 1 Send a message

The client sends information to the server , The server displays the data on the console

// client
@Test
public void client() {
Socket socket = null;
OutputStream os = null;
try {
//1. establish Socket object , Indicates the server side of ip And port number
InetAddress inet = InetAddress.getByName("192.168.14.100");
socket = new Socket(inet,8899);
//2. Get an output stream , Used to output data
os = socket.getOutputStream();
//3. The operation of writing data
os.write(" Hello , I'm the client mm".getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
//4. Closure of resources
if(os != null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(socket != null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
// Server side
@Test
public void server() {
ServerSocket ss = null;
Socket socket = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
try {
//1. Create server side ServerSocket, Indicate your own port number
ss = new ServerSocket(8899);
//2. call accept() Represents the reception of socket
socket = ss.accept();
//3. Get input stream
is = socket.getInputStream();
// It's not recommended to write , It could be messy
// 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. Read data from the input stream
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(" Received from :" + socket.getInetAddress().getHostAddress() + " The data of ");
} catch (IOException e) {
e.printStackTrace();
} finally {
if(baos != null){
//5. close resource
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();
}
}
}
}

Code example 2 Upload files

The client sends the file to the server , The server saves the file locally

@Test
public void client() throws IOException {
//1.
Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9090);
//2.
OutputStream os = socket.getOutputStream();
//3.
FileInputStream 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);
}
//5.
fis.close();
os.close();
socket.close();
}
@Test
public void server() throws IOException {
//1.
ServerSocket ss = new ServerSocket(9090);
//2.
Socket socket = ss.accept();
//3.
InputStream is = socket.getInputStream();
//4.
FileOutputStream 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.
fos.close();
is.close();
socket.close();
ss.close();
}

Code example 3 Return the document , Return information

@Test
public void client() throws IOException {
//1.
Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9090);
//2.
OutputStream os = socket.getOutputStream();
//3.
FileInputStream 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);
}
// Turn off the output of data
socket.shutdownOutput();
//5. Receiving data from the server , And display it on the console
InputStream is = socket.getInputStream();
ByteArrayOutputStream 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());
//6.
fis.close();
os.close();
socket.close();
baos.close();
}
@Test
public void server() throws IOException {
//1.
ServerSocket ss = new ServerSocket(9090);
//2.
Socket socket = ss.accept();
//3.
InputStream is = socket.getInputStream();
//4.
FileOutputStream 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(" Picture transfer complete ");
//6. The server gives the client feedback
OutputStream os = socket.getOutputStream();
os.write(" Hello , beauty , I have received the picture , Very beautiful !".getBytes());
//7.
fos.close();
is.close();
socket.close();
ss.close();
os.close();
}

Summary

Left server 、 Right client

image-20201111195701881.png

client

  • Customize
  • browser

Server side

  • Customize
  • Tomcat The server

UDP Network programming

class DatagramSocket and DatagramPacket Based on UDP Protocol network program .

UDP Datagram through datagram socket DatagramSocket Send and receive , The system does not guarantee UDP Datagrams must be delivered safely to their destinations , I'm not sure when I'll arrive

DatagramPacket Object encapsulates UDP The datagram , The datagram contains the sender's IP Address and port number as well as the receiver's IP Address and port number

UDP Each datagram in the protocol gives the complete address information , Therefore, there is no need to establish a connection between the sender and the receiver . It's like sending an express package .

technological process

  1. DatagramSocket And DatagramPacket
  2. Set up the sender , The receiver
  3. Building packets
  4. call Socket Sending of 、 Receiving method
  5. close Socket

The sender and receiver are two independent running programs

Example 1

The sender

DatagramSocket ds = null;
try {
ds = new DatagramSocket();
byte[] by = "hello,atguigu.com".getBytes();
DatagramPacket dp = new DatagramPacket(by, 0, by.length, InetAddress.getByName("127.0.0.1"), 10000);
ds.send(dp);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (ds != null)
ds.close();
}

The receiver

DatagramSocket ds = null;
try {
ds = new DatagramSocket(10000);
byte[] by = new byte[1024];
DatagramPacket dp = new DatagramPacket(by, by.length);
ds.receive(dp);
String str = new String(dp.getData(), 0, dp.getLength());
System.out.println(str + "--" + dp.getAddress());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (ds != null)
ds.close();
}

Code example

// The sender
@Test
public void sender() throws IOException {
DatagramSocket socket = new DatagramSocket();
String str = " I am a UDP Missiles sent by ";
byte[] data = str.getBytes();
InetAddress inet = InetAddress.getLocalHost();
DatagramPacket packet = new DatagramPacket(data,0,data.length,inet,9090);
socket.send(packet);
socket.close();
}
// The receiver
@Test
public void receiver() throws IOException {
DatagramSocket 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()));
socket.close();
}

URL Programming

URL(Uniform Resource Locator): Uniform resource locator , It said Internet On a certain The address of the resource .

URL Of 5 The basic structure

http://localhost:8080/examples/beauty.jpg?username=Tom

agreement Host name Port number Resources to address parameter list

How to instantiate

URL url = new URL("http://localhost:8080/examples/beauty.jpg?username=Tom");

Common methods

One URL After the object is generated , Its properties cannot be changed , But it can be given by Method to get these properties :

public String getProtocol( ) Get the URL The agreement name of
public String getHost( ) Get the URL The host name
public String getPort( ) Get the URL Port number
public String getPath( ) Get the URL File path
public String getFile( ) Get the URL The name of the file
public String getQuery( ) Get the URL The query name of
URL url = new URL("http://localhost:8080/examples/myTest.txt");
System.out.println("getProtocol() :"+url.getProtocol());
System.out.println("getHost() :"+url.getHost());
System.out.println("getPort() :"+url.getPort());
System.out.println("getPath() :"+url.getPath());
System.out.println("getFile() :"+url.getFile());
System.out.println("getQuery() :"+url.getQuery());
//=============================
getProtocol() :http
getHost() :localhost
getPort() :8080
getPath() :/examples/myTest.txt
getFile() :/examples/myTest.txt
getQuery() :null

Can read 、 Download the corresponding url resources

URLConnection: To URL Connection of the referenced remote object . When with a URL When establishing a connection , First of all, in a URL By means of objects openConnection() Generate corresponding URLConnection object . If the connection process fails , Will produce IOException.

adopt URLConnection Object to get the input stream and output stream , That is, it can be compared with the existing CGI Programs interact .

public static void main(String[] args) {
HttpURLConnection urlConnection = null;
InputStream is = null;
FileOutputStream fos = null;
try {
URL url = new URL("http://localhost:8080/examples/beauty.jpg");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
is = urlConnection.getInputStream();
fos = new FileOutputStream("day10\\beauty3.jpg");
byte[] buffer = new byte[1024];
int len;
while((len = is.read(buffer)) != -1){
fos.write(buffer,0,len);
}
System.out.println(" Download complete ");
} catch (IOException e) {
e.printStackTrace();
} finally {
// close resource
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();
}
}
}

URI、URL and URN The difference between

URI, yes uniform resource identifier, Uniform resource identifiers , Used to uniquely identify a resources . and URL yes uniform resource locator, Uniform resource locator , It's a kind of concrete Of URI, namely URL Can be used to identify a resource , It also shows how to locate This resource .

and URN,uniform resource name, Unified resource naming , Resources are identified by their names , such as mailto:[email protected]

in other words ,URI In an abstract way , high-level The sub concept defines the uniform resource identifier , and URL and URN It's a specific way to identify resources .URL and URN Is a kind of URI.

版权声明
本文为[Want to exchange steamed stuffed bun for thesis]所创,转载请带上原文链接,感谢

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云