[Learn JAVA from scratch | Article 42] Network programming for beginners

Table of contents

Foreword:

What is web programming:

Application scenarios of network programming:

Common software architecture: 

CS architecture:

BS architecture:

Three elements of network programming:​

Summarize:


Foreword:

        Today's Internet has penetrated into every aspect of our daily life, and network programming, as one of the important technologies, is playing a key role. As a widely used programming language, Java also has excellent performance and rich support in the field of network programming.

        Java network programming provides developers with powerful tools and libraries that enable them to easily build a variety of network applications, including client-side and server-side applications. Through Java's network programming capabilities, we can realize cross-platform network communication, data transmission, remote calling and real-time message delivery and other functions.

         Let us embark on this exciting journey of network process designing and explore the charm and infinite potential of Java technology. Whether you want to add new skills to daily development or pave the way for future career development, this article will be your best guide to learning and mastering Java network programming. let's start!

What is web programming:

In Java, network programming refers to the development process of using the Java language and related APIs to realize various network applications . It covers aspects such as establishing network connections, data transfer, and communication protocols. 

Network programming is the data transmission performed by programs running on different computers under the network communication protocol. 

Application scenarios of network programming:

  1. Client-Server Communication : Network programming is often used to build applications on a client-server model. Clients communicate with servers over network connections and send requests to get data or perform actions. For example, a web application communicates with a server through the HTTP protocol to obtain web page content or submit form data.

  2. Distributed systems : Network programming is used to build distributed systems where multiple computers communicate and coordinate work with each other through a network connection. Distributed systems can be used in a variety of applications, including large-scale data processing, parallel computing, cluster management, and more.

  3. Real-time communication : Network programming makes real-time communication possible, and can build instant messaging applications, video conferencing software, real-time games, etc. Data and messages are transmitted through the network, and different users can communicate and interact in real time.

  4. Remote call : Network programming allows remote methods or functions to be called on different computers to achieve distributed computing. Remote procedure call (RPC) and Web service are common remote calling technologies, which are used to implement cross-platform and cross-language method calls.

  5. Data transmission and sharing : Through network programming, data transmission and sharing between different computers can be realized. This is very common in scenarios such as large-scale data processing, file transfer, and cloud storage.

  6. Network Security and Encryption : Network programming is also closely related to network security and data encryption. Through network programming, operations such as secure data transmission, identity verification, data encryption and decryption can be realized to ensure data security and confidentiality during communication.

  7. Internet of Things (IoT) : Network programming also plays an important role in the field of IoT. Through network programming, communication and data exchange between IoT devices can be realized, so as to build applications such as smart home, smart city, and industrial automation.

 Before formally learning network programming, we must first introduce two common software architectures: CS and BS

Common software architecture: 

CS architecture:

The CS architecture , namely the Client-Server architecture, is a commonly used distributed computing architecture, which is common in computer networks. It realizes the distribution and collaboration of system functions bydividing the system into two parts : client and server .

Users are required to download and install the client program locally, and there is a server-side program remotely

In the CS architecture, the client refers to the terminal equipment used by the user, such as a personal computer, mobile phone or tablet computer, etc., which communicate with the server through the network. The client is responsible for sending requests, receiving and displaying data returned by the server, and providing user interface and interactive functions.

The server is the central control unit responsible for processing and responding to requests sent by clients. A server can be an independent computer, or a system composed of multiple computer clusters. It runs the web application, receives client requests, processes them, and sends the processed results back to the client.

The characteristics of the CS architecture are as follows:

  1. Distributed : The client and server can run on different devices and communicate through the network, so that the functions and load of the system can be distributed on different machines, improving the scalability and performance of the system.
  2. Centralization : As the central control unit, the server is responsible for processing and managing client requests and data, realizing unified management of the entire system, and easy maintenance and debugging.
  3. Loose coupling : The client and server communicate through agreed protocols, are independent of each other, and can be upgraded and improved independently without affecting the function and stability of each other.
  4. Efficiency : The server can centrally process a large amount of requests and data, realize efficient resource sharing and task allocation, and improve the concurrent processing capability and response speed of the system.

The CS architecture is widely used in various Internet applications, such as websites, e-commerce systems, social media, etc., and it provides an efficient way to implement distributed computing and services.

advantage:

  1. Distributed: The CS architecture divides the system into two parts, the client and the server, which can distribute the functions and load of the system on different machines, improving the scalability and performance of the system.
  2. Centralized management: As the central control unit, the server is responsible for processing and managing client requests and data, realizing unified management and control of the entire system, and easy maintenance and upgrades.
  3. Loose coupling: The client and server communicate through agreed protocols, are independent of each other, and can be upgraded and improved independently without affecting the function and stability of each other.
  4. Efficiency: The server centrally processes a large amount of requests and data, realizes efficient resource sharing and task allocation, and improves the concurrent processing capability and response speed of the system.

shortcoming:

  1. Single point of failure: In the CS architecture, the server is the core of the system. If the server fails or is unavailable, the entire system will not be able to operate normally, and there is a risk of a single point of failure.
  2. Communication overhead: Since the client and server communicate over the network, there is a certain amount of communication overhead, especially when communicating across networks or remotely, which may increase latency and network load.
  3. Difficult to achieve real-time: In the CS architecture, the client needs to wait for the server to respond after initiating a request. This request-response mode makes it difficult to implement applications with high real-time requirements.

BS architecture:

The BS architecture , namely the Browser-Server architecture, is a common layered architecture and one of the commonly used architectural patterns in Internet applications.

Users need to use browsers to access pages, and customers access different servers

In the BS architecture, the client accesses and uses the application program through a browser, and the server is responsible for processing the request sent by the client and sending a response. The client and server communicate over the network.

The characteristics of the BS architecture are as follows:

  1. Layered architecture : The BS architecture divides the system into two layers, namely the client layer and the server layer. The client layer includes the browser used by the user and is responsible for displaying the user interface and providing user interaction. The server layer is responsible for processing and managing data, logic processing, and interaction with the database.
  2. Centralization : As the central control unit, the server is responsible for the processing of data and business logic. The client sends a request through the browser, and the server receives the request and makes a response, realizing the centralized management and control of the system.
  3. Cross-platform : Since the client uses a browser and does not depend on a specific operating system or device, the application can run on different platforms without additional installation or update.
  4. Unified interface : In the BS architecture, users access applications through a browser, whether on a PC or a mobile device, providing a unified interface and user experience.
  5. Simplify the client : the client only needs to have a browser and a network connection, and there is no need to install complicated applications, which reduces the burden on the client.

A typical application of BS architecture is web applications, such as websites, email services, online office suites, etc. Its advantages include easy deployment and maintenance, cross-platform support, and reduced client dependencies and complexity. However, since most of the business logic is processed on the server side, the pressure on the server may be increased, and there are certain requirements for the quality and stability of the network connection.

advantage:

  1. Cross-platform: By using the browser as the client, the BS architecture can realize application program access on different operating systems and devices, without the need to develop and maintain multiple client versions for different platforms, which improves development efficiency.
  2. Simplify the client: Since the client is mainly a browser, there is no need to install complicated applications, and most of the functions are completed by the server, which reduces the resource occupation and complexity of the user's device.
  3. Centralized control and management: The BS architecture concentrates the core data and business logic on the server side, which makes the management and maintenance of the system more centralized and convenient, and can be quickly upgraded and improved.
  4. Unified interface and experience: All user interface and operations are completed through the browser, providing a unified interface and user experience, reducing the user's learning costs and adaptation time.

shortcoming:

  1. Requirements for network connection and bandwidth: BS architecture applications need to be accessed and operated through a network connection server, and have certain requirements for the quality and stability of the network connection. If the network is unstable or the bandwidth is limited, it may lead to a decline in user experience.
  2. Increased server pressure: Since most of the business logic is processed on the server side, the server needs to undertake more computing and processing work, and needs to have sufficient performance and scalability, otherwise it may face performance bottlenecks or instability.
  3. Reliance on the server: In the BS architecture, the core functions and data of the system are stored on the server side. If the server fails or is unavailable, users will not be able to access or use the system.
  4. Privacy and security issues: Since user data and sensitive information are stored on the server side, the security requirements for the server are relatively high, and corresponding security measures need to be taken to protect the privacy of user data and the security of the system.

Three elements of network programming:

  1. IP address (Internet Protocol Address) : An IP address is a unique identifier used to identify and locate a device on the network. IPV4 consists of 4 bytes, usuallyexpressed in dotted decimal (that is, expressing the four bytes as numbers) (such as 192.168.0.1). In network programming, the IP address is used to identify the target host to connect to or the network interface to listen on.

  2. Port Number (Port Number) : The port number is used to identify a specific application or service. It is a 16-bit number ranging from 0 to 65535. Among them, 0 to 1023 are reserved as commonly used well-known ports for some specific services, such as port 80 of HTTP, port 443 of HTTPS, etc. In network programming, clients and servers communicate and distinguish through different port numbers.

  3. Protocol (Protocol) : The protocol defines the rules and conventions in network communication. Common network protocols include TCP (Transmission Control Protocol), UDP (User Datagram Protocol), and HTTP (Hypertext Transfer Protocol). TCP provides reliable, connection-oriented communication, suitable for applications that require reliable transmission; UDP provides connectionless communication, suitable for applications with high real-time requirements; HTTP is an application layer protocol, used to transmit super text and other data.

These three elements play an important role in network programming. Clients and servers establish connections through IP addresses and port numbers, communicate using specific protocols, and realize data interaction and transmission. Other concepts and technologies in network programming, such as sockets (Socket), HTTP requests and responses, network transport layers, etc., are all developed around these three elements.

We want to focus on introducing the UDP protocol and the TCP protocol in the protocol. It is recommended that you memorize them directly:

UDP protocol:

  • User Datagram Protocol
  • UDP is a connectionless communication protocol
  • The speed is fast, there is a size limit, and a maximum of 64K can be sent at a time, and the data is not safe and easy to lose

The UDP protocol works as follows:

  1. The application divides the data to be transmitted into smaller packets (datagrams).
  2. The datagram adds a UDP protocol header, including information such as source port and destination port.
  3. Send the datagram to the target host.
  4. The receiver hands over the datagram to the corresponding application for processing according to the port information in the UDP header.
  5. The receiver does not send any confirmation reply, and does not perform error handling such as retransmission.

The UDP protocol is suitable for application scenarios with high real-time requirements and low data reliability requirements, such as real-time video transmission, audio streaming, etc. In these scenarios, a slight loss of data will not have much impact on the execution of the application.

public class UDPtest {
    public static void main(String[] args) {
        // 启动服务器端
        new Thread(new UDPServer()).start();
        // 启动客户端
        new Thread(new UDPClient()).start();
    }
}

class UDPServer implements Runnable {
    @Override
    public void run() {
        try {
            // 创建服务器端Socket对象,监听指定端口号
            DatagramSocket serverSocket = new DatagramSocket(8888);

            byte[] receiveData = new byte[1024];

            while (true) {
                // 创建接收数据包
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

                // 接收数据
                serverSocket.receive(receivePacket);

                // 解析接收到的数据
                String message = new String(receivePacket.getData(), 0, receivePacket.getLength());
                System.out.println("Server received: " + message);

                // 发送响应数据
                InetAddress IPAddress = receivePacket.getAddress();
                int port = receivePacket.getPort();
                String responseMessage = "Hello, client!";
                byte[] sendData = responseMessage.getBytes();
                DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
                serverSocket.send(sendPacket);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class UDPClient implements Runnable {
    @Override
    public void run() {
        try {
            // 创建客户端Socket对象
            DatagramSocket clientSocket = new DatagramSocket();

            // 设置服务器端IP地址和端口号
            InetAddress IPAddress = InetAddress.getByName("localhost");
            int port = 8888;

            // 发送数据
            String message = "Hello, server!";
            byte[] sendData = message.getBytes();
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
            clientSocket.send(sendPacket);

            // 创建接收数据包
            byte[] receiveData = new byte[1024];
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

            // 接收数据
            clientSocket.receive(receivePacket);

            // 解析接收到的数据
            String responseMessage = new String(receivePacket.getData(), 0, receivePacket.getLength());
            System.out.println("Client received: " + responseMessage);

            // 关闭Socket连接
            clientSocket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

TCP protocol:

  • Transmission Control Protocol TCP (Transmission Control Protocol)
  • TCP is a connection -oriented communication protocol
  • Slow speed, no size limit, data security

The TCP protocol works as follows:

  1. Initiate a connection: the sender sends a SYN (synchronization) packet to the receiver, and the receiver replies with a SYN+ACK packet after receiving it, and the sender replies with an ACK packet to complete the establishment of the connection.
  2. Data transmission: After the connection is established, the sender divides the data into smaller data segments and adds TCP header information, including serial number, confirmation number, etc. The sender sends the data segment to the receiver.
  3. Data confirmation: After receiving the data segment, the receiver will send an acknowledgment ACK, indicating that the data segment has been received; the sender will send the next data segment after receiving the ACK.
  4. Congestion control: If there is congestion in the network, the receiver will control the flow through the congestion window, and the sender will adjust the congestion window according to the received ACK to avoid network congestion.
  5. Connection close: When the data transmission is complete, the sender and receiver can initiate the close of the connection. The sender sends a FIN packet, the receiver replies with an ACK packet after receiving it, then sends a FIN packet, and finally the sender replies with an ACK packet to complete the closing of the connection.

The TCP protocol is suitable for application scenarios that require high data reliability and order, such as file transfer, email, and web browsing. Although the overhead of the TCP protocol is large, its reliability and orderliness allow data to be transmitted in the correct order, and can ensure that data is not lost or damaged.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class TCPClientServer {
    public static void main(String[] args) {
        // 启动服务器端
        new Thread(new TCPServer()).start();
        // 启动客户端
        new Thread(new TCPClient()).start();
    }
}

class TCPServer implements Runnable {
    @Override
    public void run() {
        try {
            // 创建服务器端Socket对象,监听指定端口号
            java.net.ServerSocket serverSocket = new java.net.ServerSocket(8888);

            while (true) {
                // 等待客户端连接
                Socket clientSocket = serverSocket.accept();
                System.out.println("Server connected");

                // 获取输入流和输出流
                BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);

                // 读取客户端发送的数据
                String message = in.readLine();
                System.out.println("Server received: " + message);

                // 发送响应数据
                String responseMessage = "Hello, client!";
                out.println(responseMessage);

                // 关闭连接
                clientSocket.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class TCPClient implements Runnable {
    @Override
    public void run() {
        try {
            // 创建客户端Socket对象,连接服务器
            Socket clientSocket = new Socket("localhost", 8888);
            System.out.println("Client connected");

            // 获取输入流和输出流
            BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);

            // 发送数据
            String message = "Hello, server!";
            out.println(message);

            // 读取服务器端发送的响应数据
            String responseMessage = in.readLine();
            System.out.println("Client received: " + responseMessage);

            // 关闭连接
            clientSocket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Summarize:

        This is the end of our introduction to network programming today, and we will introduce other knowledge points in network programming in detail later. There are many knowledge points in network programming, so we need to remember more, so that we can master network programming proficiently

If my content is helpful to you, please like, comment and bookmark . Creation is not easy, everyone's support is my motivation to persevere!

 

Guess you like

Origin blog.csdn.net/fckbb/article/details/132164455