This article will give you a deep understanding of [Java Basics] Network Programming (Part 1)

written in front


        Hello everyone, I am [ Lin-Xiaobai ], a student majoring in software engineering , who likes computer knowledge . I hope everyone can learn and progress together ! I am a college student , and my professional level is limited. If you find any mistakes or deficiencies , please correct me! thank you all! ! !

        If brothers and sisters are interested in my articles, please don't be stingy with your little hands, give more likes and follow ! ❤❤❤ Love you guys! ! !


Table of contents

written in front

1. Overview of network programming

1.1 Network Basics

 2. Overview of network communication elements

2.1 How to realize the communication between the hosts in the network

2.2 Network communication protocol

2.3 Encapsulation and unpacking of data

3. Communication element 1: IP and port number

3.1 IP address (InetAddress)

3.2 Port number

3.3 InetAddress class

3.4 InetAddress class code demonstration

4. Communication Element 2: Network Protocol

4.1 Network communication protocol

4.2 TCP/IP Protocol Cluster

4.3 TCP and UDP

4.4 Socket

epilogue


【Past review】

This article will give you a deep understanding of [Java Basics] IO Stream (Part 1)

This article will give you an in-depth understanding of [Java Basics] Generics

This article will give you an in-depth understanding of [Java Basics] Java Collections (Part 1)

This article will give you a deep understanding of [Java Basics] Notes

This article will give you a deep understanding of [Java Basics] Enumeration Classes

This article will give you a deep understanding of [Java Basics] Commonly used classes (Part 1)

This article will give you an in-depth understanding of [Java Basics] Multithreading (Part 1)


1. Overview of network programming


1.1 Network Basics

  • Java is a language on the Internet . It provides support for network applications at the language level, and programmers can easily develop common network applications.
  • The network class library provided by Java can realize painless network connection. The underlying details of networking are hidden in Java 's native installation system and controlled by the JVM . Moreover, Java implements a cross-platform network library, and programmers are faced with a unified network programming environment.
computer network:
  • Interconnect computers distributed in different geographic regions and specialized external devices with communication lines to form a large-scale and powerful network system, so that many computers can easily transmit information to each other, share hardware, software, data information and other resources .
Purpose of network programming:
  • Data exchange and communication with other computers directly or indirectly through network protocols.
There are two main problems in network programming:
  • How to accurately locate one or more hosts on the network; locate specific applications on a host
  • How to transfer data reliably and efficiently after finding the host

 2. Overview of network communication elements


2.1  How to realize the communication between the hosts in the network

Address of both parties
  • IP
  • The port number
Certain rules (ie: network communication protocol. There are two sets of reference models)
  • OSI reference model : the model is too idealized and has not been widely promoted on the Internet
  • TCP/IP Reference Model ( or TCP/IP Protocol ) : The de facto international standard.

2.2  Network communication protocol


2.3 Encapsulation and unpacking of data


3. Communication element 1: IP and port number


3.1 IP address ( InetAddress)

  • Uniquely identifies a computer (communicating entity) on the Internet
  • Local loopback address (hostAddress) : 127.0.0.1 Host name (hostName) : localhost
  • IP address classification method 1 : IPV4 and IPV6
    • IPV4 : 4 bytes , 4 0-255 . About 4.2 billion, 3 billion in North America, 400 million in Asia. Early 2011 was exhausted. Expressed in dotted decimal, such as 192.168.0.1
    • IPV6 : 128 bits ( 16 bytes), written as 8 unsigned integers, each integer is represented by four hexadecimal digits, and the numbers are separated by colons (:), such as: 3ffe:3201:1401:1280 :c8ff:fe4d:db39:1984
  • IP address classification method 2 : public network address ( used by World Wide Web ) and private address ( used by LAN ) . The beginning of 192.168. is the private address, the range is 192.168.0.0--192.168.255.255 , which is specially for internal use of the organization
  • Features: not easy to remember

3.2  Port number

  • The port number identifies the process (program) that is running on the computer
  • Different processes have different port numbers
  • It is specified as a 16 -bit integer 0~65535 .
Port classification:
well-known port
  • 0~1023 . Occupied by predefined service communication (eg: HTTP occupies port 80, FTP occupies port 21 , Telnet occupies port 23 )
register port
  • 1024~49151 . Assigned to a user process or application. (For example: Tomcat occupies port 8080 , MySQL occupies port 3306 , Oracle occupies port 1521, etc.).
Dynamic / Private Port
  • 49152~65535
The combination of port number and IP address yields a network socket: Socket .

3.3  InetAddress class

  • Hosts on the Internet have two ways to represent addresses:
    • HostName : www.atguigu.com _
    • IP address (hostAddress) : 202.108.35.210
  • The InetAddress class mainly represents the IP address, and has two subclasses: Inet4Address and Inet6Address .
  • The InetAddress class object contains the domain name and IP address of an Internet host address : www.atguigu.com and 202.108.35.210 .
  • The domain name is easy to remember. When you enter the domain name of a host when connecting to the network, the domain name server (DNS) is responsible for converting the domain name into an IP address, so that a connection can be established with the host. ------- Domain name analysis
The InetAddress class does not provide a public constructor, but provides the following static methods to obtain InetAddress instances
  • public static InetAddress getLocalHost()
  • public static InetAddress getByName(String host)
InetAddress provides the following commonly used methods
  • public String getHostAddress() : Returns the IP address string (in text form).
  • public String getHostName() : Get the hostname of this IP address
  • public boolean isReachable(int timeout) : Test whether the address can be reached

3.4 InetAddress class code demonstration

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 一、网络编程中有两个主要的问题:
 * 1.如何准确地定位网络上一台或多台主机;定位主机上的特定的应用
 * 2.找到主机后如何可靠高效地进行数据传输
 *
 * 二、网络编程中的两个要素:
 * 1.对应问题一:IP和端口号
 * 2.对应问题二:提供网络通信协议:TCP/IP参考模型(应用层、传输层、网络层、物理+数据链路层)
 *
 * 三、通信要素一:IP和端口号
 * 1. IP:唯一的标识 Internet 上的计算机(通信实体)
 * 2. 在Java中使用InetAddress类代表IP
 * 3. IP分类:IPv4 和 IPv6 ; 万维网 和 局域网
 * 4. 域名:   www.baidu.com   www.mi.com  www.sina.com  www.jd.com  www.vip.com
 * 5. 本地回路地址:127.0.0.1 对应着:localhost
 * 6. 如何实例化InetAddress:两个方法:getByName(String host) 、 getLocalHost()
 *        两个常用方法:getHostName() / getHostAddress()
 * 7. 端口号:正在计算机上运行的进程。
 * 要求:不同的进程有不同的端口号
 * 范围:被规定为一个 16 位的整数 0~65535。
 * 8. 端口号与IP地址的组合得出一个网络套接字:Socket
 * @author 麟-小白
 */
public class InetAddressTest {
    public static void main(String[] args) {
        try {
            //File file = new File("hello.txt");
            InetAddress inet1 = InetAddress.getByName("192.168.10.14");

            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());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
}

4. Communication Element 2: Network Protocol


4.1  Network communication protocol

network communication protocol
  • To achieve communication in a computer network, there must be some agreements, that is, communication protocols, and standards for speed, transmission code, code structure, transmission control steps, and error control .
Problem: Network protocols are too complex
  • Computer network communication involves a lot of content, such as specifying source and destination addresses, encryption and decryption, compression and decompression, error control, flow control, routing control, how to implement such a complex network protocol?
The idea of ​​communication protocol layering
  • When developing a protocol, break down complex components into simpler ones and compound them. The most commonly used composite method is the hierarchical method, that is, the same layer can communicate, the upper layer can call the lower layer, and has no relationship with the next layer . Each layer does not affect each other, which is conducive to the development and expansion of the system.

4.2  TCP/IP Protocol Cluster

  • There are two very important protocols in the transport layer protocol:
    • Transmission Control Protocol TCP (Transmission Control Protocol)
    • User Datagram Protocol UDP (User Datagram Protocol) .
  • TCP/IP is named after its two main protocols: Transmission Control Protocol (TCP) and Internet Protocol (IP) . It is actually a set of protocols, including multiple interrelated protocols with different functions.
  • The IP (Internet Protocol) protocol is the main protocol of the network layer, supporting the data communication between the Internet.
  • From a more practical point of view, the TCP/IP protocol model forms an efficient four-layer architecture, namely the physical link layer, IP layer, transport layer and application layer .

4.3  TCP and UDP

TCP protocol:
  • Before using the TCP protocol, a TCP connection must be established to form a transmission data channel
  • Before transmission, the " three-way handshake " method, point-to-point communication, is reliable
  • Two application processes that communicate with the TCP protocol: client and server.
  • A large amount of data can be transferred in the connection
  • After the transmission is completed, the established connection needs to be released , which is inefficient
UDP protocol:
  • Encapsulate data, source, and destination into packets without establishing a connection
  • The size of each datagram is limited to 64K
  • The sender does not care whether the other party is ready, and the receiver does not confirm receipt, so it is unreliable
  • Can broadcast
  • There is no need to release resources at the end of sending data , with low overhead and fast speed


4.4 Socket

  • The use of sockets (Socket) to develop network applications has long been widely used, so that it has become a de facto standard.
  • The combination of the uniquely identified IP address and port number on the network constitutes a uniquely identifiable identifier socket.
  • There must be Socket at both ends of the communication , which is the endpoint of communication between two machines.
  • Network communication is actually communication between Sockets .
  • Socket allows programs to treat network connections as a stream, and data is transmitted between two Sockets through IO .
  • Generally, the application that initiates the communication is the client , and the application that waits for the communication request is the server.

Socket classification:

  • Stream socket ( stream socket ): use TCP to provide reliable byte stream services
  • Datagram socket ( datagram socket ): Provides "best effort" datagram service using UDP
Common constructors of the Socket class:
  • public Socket(InetAddress address, int port) creates a stream socket and connects it to the specified port number at the specified IP address.
  • public Socket(String host, int port) creates a stream socket and connects it to the specified port number on the specified host.
Common methods of the Socket class:
  • public InputStream getInputStream() Returns this socket's input stream. Can be used to receive network messages
  • public OutputStream getOutputStream() Returns this socket's output stream. Can be used to send network messages
  • public InetAddress getInetAddress() The remote IP address to which this socket is connected , or null if the socket is not connected .
  • public InetAddress getLocalAddress() Gets the local address bound to the socket. That is, the local IP address
  • public int getPort() The remote port number to which this socket is connected, or 0 if the socket is not yet connected .
  • public int getLocalPort() Returns the local port this socket is bound to. Returns -1 if the socket has not been bound . That is, the port number of the local end.
  • public void close() closes this socket. Once a socket is closed, it cannot be used for further network connections (i.e. it cannot be reconnected or rebinded). A new socket object needs to be created. Closing this socket will also close the socket's InputStream and OutputStream.
  • public void shutdownInput() If something is read from the socket input stream after shutdownInput() has been called on the socket , the stream will return EOF (End of File). That is, no more data can be received from this socket's input stream.
  • public void shutdownOutput() Disables the output stream for this socket. For TCP sockets, any previously written data will be sent, followed by TCP 's normal connection termination sequence. The socket output stream will throw an IOException if writing to the socket output stream after shutdownOutput() has been called on the socket . That is, no data can be sent over this socket's output stream.

epilogue


I will continue to update the article! I hope everyone will click three times , your encouragement is the motivation for the author to keep updating

Guess you like

Origin blog.csdn.net/qq_34025246/article/details/128425856