Technology Sharing

Java Advanced Key Knowledge Points-23-Network Programming

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

Introduction to Network Programming

Software Structure

  • C/S structure: The full name is Client/Server structure, which refers to the client and server structure.
  • B/S structure: The full name is Browser/Server structure, which refers to the browser and server structure.

Network communication protocols

网络通信协议:通信协议是对计算机必须遵守的规则,只有遵守这些规则,计算机之间才能进行通信。

  • TCP/IP protocol: Transmission Control Protocol/Internet Protocol, is
    The most basic and widely used protocol on the Internet.
    insert image description here

Protocol Classification

java.net 包中提供了两种常见的网络协议的支持

  1. TCP: Transmission Control Protocol. TCP is a connection-oriented communication protocol, which means that before transmitting data, a logical connection is established between the sender and the receiver, and then the data is transmitted. It provides reliable and error-free data transmission between two computers.
  2. UDP: User Datagram Protocol. UDP is a connectionless protocol. When transmitting data, there is no need to establish a connection. Regardless of whether the other party's service is started, the data, data source and destination are directly encapsulated in a data packet and sent directly. The size of each data packet is limited to 64k. It is an unreliable protocol. Because it is connectionless, the transmission speed is fast, but data loss is easy.

Three-way handshake in TCP: In the TCP protocol, during the preparation phase for sending data, there are three interactions between the client and the server to ensure a reliable connection.

  • In the first handshake, the client sends a connection request to the server and waits for the server to confirm.
  • In the second handshake, the server sends a response back to the client, notifying the client that it has received the connection request.
  • In the third handshake, the client sends a confirmation message to the server again to confirm the connection.

Three elements of network programming

  1. Protocol: Rules that must be followed for computer network communications
  2. IP address: refers to Internet Protocol Address, commonly known as IP. IP address is used to give a unique number to a computer device in a network.
  • IPv4: is a 32-bit binary number, usually divided into 4 bytes, expressed in the form of abcd, such as 192.168.65.100. Among them, a, b, c, d are all decimal integers between 0 and 255, so a maximum of 4.2 billion can be expressed.
  • A 128-bit address length is used, with each group of 16 bytes divided into 8 groups of hexadecimal numbers, expressed as ABCD:EF01:2345:6789:ABCD:EF01:2345:6789, which solves the problem of insufficient network address resources.
    Common commands:
  • ipconfig【View the local IP address】
    insert image description here
  • Ping space IP address [check whether the network is connected]
  1. The port number
  • An integer represented by two bytes, with a value range of 0 to 65535. Among them, port numbers between 0 and 1023 are used by some well-known network
    For network services and applications, ordinary applications need to use port numbers above 1024. If the port number is occupied by another service or application, the current program will fail to start.
    Identify processes in the network: 协议 + IP地址 + 端口号

TCP communication program

TCP通信能实现两台计算机之间的数据交互,通信的两端,要严格区分为客户端(Client)与服务端(Server)。

Communication steps

  • The server program needs to be started in advance and wait for the client to connect.
  • The client actively connects to the server, and communication can only be achieved after the connection is successful. The server cannot actively connect to the client.

In Java, two classes are provided for implementing TCP communication programs:

  1. Client: Represented by the java.net.Socket class. Create a Socket object, send a connection request to the server, the server responds to the request, and the two establish a connection and start communicating.
  2. Server: java.net.ServerSocket class. Creating a ServerSocket object is equivalent to starting a service and waiting for client connections.

Socket Class

Socket 类:该类实现客户端套接字,套接字指的是两台设备之间通讯的端点。
Construction method:
public Socket(String host, int port) : Creates a socket object and connects it to the specified port number on the specified host. If the specified host is null, it is equivalent to specifying the loopback address (Loopback Address (127.xxx) is the local loopback address.)。
Member methods:

  • public InputStream getInputStream() : Returns the input stream for this socket.
  • public OutputStream getOutputStream() : Returns the output stream of this socket.
  • public void close() : Close this socket.
  • public void shutdownOutput() : Disables the output stream for this socket.

ServerSocket Class

ServerSocket 类:这个类实现了服务器套接字,该对象等待通过网络的请求。
Construction method:
public ServerSocket(int port): Use this constructor to create a ServerSocket object and bind it to a specified port.
The parameter port is the port number.
Member methods:
public Socket accept() : Listen and accept connections, and return a new Socket object for communicating with the client.
Will block until a connection is established.

Simple TCP network program

TCP communication analysis:

  1. [Server] Start, create a ServerSocket object, and wait for connection.
  2. [Client] Start, create a Socket object, and request a connection.
  3. [Server] Receives the connection, calls the accept method, and returns a Socket object.
  4. [Client] Socket object, get OutputStream, and write data to the server.
  5. [Server] Socket object, get InputStream, and read the data sent by the client.
  6. [Server] Socket object, get OutputStream, and write data back to the client.
  7. [Client] Scoket object, get InputStream, parse and write back data.
  8. 【Client】Release resources and disconnect.

Code example:

  • Service-Terminal:
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerTCP {
    public static void main(String[] args) throws IOException {
        System.out.println("服务端启动 , 等待连接 .... ");
        // 1.创建 ServerSocket对象,绑定端口,开始等待连接
        ServerSocket ss = new ServerSocket(6666);
        // 2.接收连接 accept 方法, 返回 socket 对象.
        Socket server = ss.accept();
        // 3.通过socket 获取输入流
        InputStream is = server.getInputStream();
        // 4.一次性读取数据
        // 4.1 创建字节数组
        byte[] b = new byte[1024];
        // 4.2 据读取到字节数组中.
        int len = is.read(b);
        // 4.3 解析数组,打印字符串信息
        String msg = new String(b, 0, len);
        System.out.println(msg);
        //5.关闭资源.
        is.close();
        server.close();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

The server specifies the port number, obtains the Socket object through the accept() method, obtains the input stream through the client object, and finally reads the data and waits for the message sent by the client.

  • Client
import java.net.Socket;

public class ClientTCP {
    public static void main(String[] args) throws Exception {
        System.out.println("客户端 发送数据");
        // 1.创建 Socket ( ip , port ) , 确定连接到哪里.
        Socket client = new Socket("localhost", 6666);
        // 2.获取流对象 . 输出流
        OutputStream os = client.getOutputStream();
        // 3.写出数据.
        os.write("你好么? tcp ,我来了".getBytes());
        // 4. 关闭资源 .
        os.close();
        client.close();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

When the client is created, the IP address and port number of the connection are specified to facilitate connecting to the server, obtaining the output stream and outputting data through the client Socket object.
insert image description here

File upload【Extended】

  1. 【Client】Input stream, reads file data from the hard disk into the program.
  2. 【Client】Output stream, write file data to the server.
  3. 【Server】Input stream, read file data to the server program.
  4. [Server] Output stream, write file data to the server hard disk.
  5. [Server] Get the output stream and write back the data.
  6. [Client] Get the input stream and parse and write back the data.

数据准备:Place a file named test.jpg under drive D and create a folder called test

Code example:

  • Server
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class FileUpload_Server {
    public static void main(String[] args) throws IOException {
        System.out.println("服务器 启动..... ");
        // 1. 创建服务端ServerSocket
        ServerSocket serverSocket = new ServerSocket(6666);
        // 2. 循环接收,建立连接
        while (true) {
        Socket accept = serverSocket.accept();
            /* 3. socket对象交给子线程处理,进行读写操作Runnable接口中,只有一个run方法,使用lambda表达式简化格式 */
            new Thread(() -> {
                try (   //3.1 获取输入流对象
                        BufferedInputStream bis = new BufferedInputStream(accept.getInputStream());
                        //3.2 创建输出流对象, 保存到本地 .
                        FileOutputStream fis = new FileOutputStream("D:/test/" + System.currentTimeMillis() + ".jpg");
                        BufferedOutputStream bos = new BufferedOutputStream(fis)) {
                    // 3.3 读写数据
                    byte[] b = new byte[1024 * 8];
                    int len;
                    while ((len = bis.read(b)) != -1) {
                        bos.write(b, 0, len);
                    }

                    // 4.=======信息回写===========================
                    System.out.println("back ........");
                    OutputStream out = accept.getOutputStream();
                    out.write("上传成功".getBytes());
                    out.close();

                    //5. 关闭 资源
                    bos.close();
                    bis.close();
                    accept.close();
                    System.out.println("文件上传已保存");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44

Here, a server object is first created, and while(true) is used to ensure the continuous connection to the server. Then, a thread is started to ensure that when one user uploads a large file, the efficiency of uploading files by other users will not be affected. The file name is set using the system milliseconds + '.jpg' to ensure that the same file name will not be overwritten during upload.

  • Client
import java.io.*;
import java.net.Socket;

public class FileUpload_Client {
    public static void main(String[] args) throws IOException {
        // 1.创建流对象
        // 1.1 创建输入流,读取本地文件
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\test.jpg"));
        // 1.2 创建输出流,写到服务端
        Socket socket = new Socket("localhost", 6666);
        BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
        //2.写出数据.
        byte[] b = new byte[1024 * 8 ];
        int len ;
        while (( len = bis.read(b))!=-1) {
            bos.write(b, 0, len);
        }
        // 关闭输出流,通知服务端,写出数据完毕
        socket.shutdownOutput();
        System.out.println("文件发送完毕");   
        // 3. =====解析回写============
        InputStream in = socket.getInputStream();
        byte[] back = new byte[20];
        in.read(back);
        System.out.println(new String(back));
        in.close();
        // ============================
        // 4.释放资源
        socket.close();
        bis.close();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

insert image description here
insert image description here
Here we can see that our server successfully saved the file sent by the user to the hard disk.

Java enthusiasts are welcome to read the article. The author will continue to update it. I look forward to your attention and collection. . .