Java language foundation Day27 (network programming, TCP communication program, comprehensive case)

1, Network programming

1. Software structure

  • C/S structure: the full name is Client/Server structure, which refers to client and server structure. Common programs include QQ, Xunlei and other software.
  • B/S structure: fully known as Browser/Server structure, it refers to browser and server structure. Common browsers include Google, Firefox, etc.


The two architectures have their own advantages, but no matter which architecture, it is inseparable from the support of the network. Network programming is a program that realizes the communication between two computers under a certain protocol.

2. Network communication protocol

  • Network communication protocol: communication protocol is the rules that must be observed by computers. Only by observing these rules can computers communicate with each other. This is just like a car driving on the road must abide by the traffic rules. The protocol has unified provisions on the data transmission format, transmission rate and transmission steps. Both sides of the communication must abide by them at the same time and finally complete the data exchange.
  • TCP/IP protocol: Transmission Control Protocol / Internet protocol, which is the most basic and extensive protocol on the Internet. It defines standards for how computers connect to the Internet and how data is transmitted between them. It contains a series of protocols for processing data communication, and adopts a 4-layer layered model. Each layer calls the protocols provided by its next layer to complete its own requirements

3. Classification of network communication protocols

The communication protocol is still relatively complex, Java Net package, which provides low-level communication details. We can directly use these classes and interfaces to focus on network program development without considering the details of communication.
java.net package provides support for two common network protocols:


4. Three elements of network programming

agreement

  • Protocol: the rules that must be observed in computer network communication have been introduced and will not be repeated.

IP address

  • Protocol address, commonly known as Internet Protocol Address. IP addresses are used to uniquely number computer devices in a network. If we compare "personal computer" to "a telephone", then "IP address" is equivalent to "telephone number".

  • IP address classification

    IPv4: it is a 32-bit binary number, which is usually divided into 4 bytes and expressed in the form of a.b.c.d, such as 192.168.65.100. Where a, B, C and D are decimal integers between 0 and 255, then they can represent 4.2 billion at most.

    IPv6: due to the vigorous development of the Internet, the demand for IP address is increasing, but the limited network address resources make the allocation of IP more and more tense. Data show that the global IPv4 address was allocated in February 2011.

    In order to expand the address space, it is proposed to redefine the address space through IPv6. It adopts 128 bit address length, a group of 16 bytes, which is divided into 8 groups of hexadecimal numbers, expressed as ABCD:EF01:2345:6789:ABCD:EF01:2345:6789. It is said that it can compile a network address for every grain of sand in the world, which solves the problem of insufficient network address resources.

    Common commands

    • Check the local IP address and enter in the console:

    ipconfig

    • Check whether the network is connected. Enter:

    ping blank IP address
    ping 220.181.57.216

    Special IP address

    • Local IP address: 127.0.0.1, localhost.

Port number

2, TCP communication program

1. Overview of TCP communication

2. Client code implementation of TCP communication

package com.itheima.demo01.TCP;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/*
    TCP Communication client: send connection request to the server, send data to the server, and read the data written back by the server
    Class representing the client:
        java.net.Socket:This class implements client sockets (also known as "sockets"). A socket is the endpoint of communication between two machines.
        Socket: a network unit that contains an IP address and port number

    Construction method:
        Socket(String host, int port) Create a stream socket and connect it to the specified port number on the specified host.
        Parameters:
            String host:Server host name / server IP address
            int port:Port number of the server

    Member method:
        OutputStream getOutputStream() Returns the output stream of this socket.
        InputStream getInputStream() Returns the input stream for this socket.
        void close() Close this socket.

    Implementation steps:
        1.Create a client object Socket, and the construction method binds the IP address and port number of the server
        2.Use the method getOutputStream() in the Socket object to obtain the network byte output stream OutputStream object
        3.Use the write method in the OutputStream object of the network byte output stream to send data to the server
        4.Use the method getInputStream() in the Socket object to obtain the network byte input stream InputStream object
        5.Use the read method in the InputStream object of the network byte input stream to read the data written back by the server
        6.Free resources (Socket)
     be careful:
        1.When interacting with the server, the client must use the network flow provided in the Socket, not the flow object created by itself
        2.When we create a client object Socket, we will ask the server to establish a connection path through three handshakes
            At this time, if the server is not started, an exception connectexception: connection rejected: connect will be thrown
            If the server is started, you can interact
 */
public class TCPClient {
    public static void main(String[] args) throws IOException {
        //1. Create a client object Socket and bind the IP address and port number of the server with the construction method
        Socket socket = new Socket("127.0.0.1",8888);
        //2. Use the method getOutputStream() in the Socket object to obtain the network byte output stream OutputStream object
        OutputStream os = socket.getOutputStream();
        //3. Use the write method in the OutputStream object of the network byte output stream to send data to the server
        os.write("Hello server".getBytes());

        //4. Use the method getInputStream() in the Socket object to obtain the network byte input stream InputStream object
        InputStream is = socket.getInputStream();

        //5. Use the read method in the InputStream object of the network byte input stream to read the data written back by the server
        byte[] bytes = new byte[1024];
        int len = is.read(bytes);
        System.out.println(new String(bytes,0,len));

        //6. Release resources (Socket)
        socket.close();

    }

}

package com.itheima.demo01.TCP;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/*
    TCP Server side of communication: receive the request from the client, read the data sent by the client, and write back the data to the client
    Class representing the server:
        java.net.ServerSocket:This class implements server sockets.

    Construction method:
        ServerSocket(int port) Create a server socket bound to a specific port.

    The server side must be clear about one thing. It must know which client requests the server
    Therefore, you can use the accept method to obtain the requested client object Socket
    Member method:
        Socket accept() Listen and accept connections to this socket.

    Implementation steps of the server:
        1.Create the server ServerSocket object and the port number to be specified by the system
        2.Use the method accept in the ServerSocket object to obtain the requested client object Socket
        3.Use the method getInputStream() in the Socket object to obtain the network byte input stream InputStream object
        4.Use the read method in the InputStream object of the network byte input stream to read the data sent by the client
        5.Use the method getOutputStream() in the Socket object to obtain the network byte output stream OutputStream object
        6.Use the write method in the OutputStream object of the network byte output stream to write back data to the client
        7.Release resources (Socket,ServerSocket)
 */
public class TCPServer {
    public static void main(String[] args) throws IOException {
        //1. Create the server ServerSocket object and the port number to be specified by the system
        ServerSocket server = new ServerSocket(8888);
        //2. Use the method accept in the ServerSocket object to obtain the requested client object Socket
        Socket socket = server.accept();
        //3. Use the method getInputStream() in the Socket object to obtain the network byte input stream InputStream object
        InputStream is = socket.getInputStream();
        //4. Use the read method in the InputStream object of the network byte input stream to read the data sent by the client
        byte[] bytes = new byte[1024];
        int len = is.read(bytes);
        System.out.println(new String(bytes,0,len));
        //5. Use the method getOutputStream() in the Socket object to obtain the network byte output stream OutputStream object
        OutputStream os = socket.getOutputStream();
        //6. Use the write method in the OutputStream object of the network byte output stream to write back data to the client
        os.write("Yes, thank you".getBytes());
        //7. Release resources (Socket,ServerSocket)
        socket.close();
        server.close();
    }
}

3, Comprehensive case

1. Principle of file upload

2. Client of file upload case

package com.itheima.demo02.FileUpload;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/*
    The client of the file upload case: read the local file, upload it to the server, and read the data written back by the server

    to make clear:
        Data source: C: \ \ 1 jpg
        Destination: Server

    Implementation steps:
        1.Create a local byte input stream FileInputStream object and bind the data source to be read in the construction method
        2.Create a client Socket object and bind the IP address and port number of the server in the construction method
        3.Use the method getOutputStream in the Socket to obtain the network byte output stream OutputStream object
        4.Use the read method in the FileInputStream object of the local byte input stream to read the local file
        5.Use the write method in the OutputStream object of the network byte output stream to upload the read file to the server
        6.Use the method getInputStream in Socket to obtain the InputStream object of network byte input stream
        7.Use the read method in the InputStream object of the network byte input stream to read the data written back by the service
        8.Release resources (FileInputStream,Socket)
 */
public class TCPClient {
    public static void main(String[] args) throws IOException {
        //1. Create a local byte input stream FileInputStream object and bind the data source to be read in the construction method
        FileInputStream fis = new FileInputStream("c:\\1.jpg");
        //2. Create a client Socket object and bind the IP address and port number of the server in the construction method
        Socket socket = new Socket("127.0.0.1",8888);
        //3. Use the method getOutputStream in the Socket to obtain the network byte output stream OutputStream object
        OutputStream os = socket.getOutputStream();
        //4. Use the read method in the FileInputStream object of the local byte input stream to read the local file
        int len = 0;
        byte[] bytes = new byte[1024];
        while((len = fis.read(bytes))!=-1){
            //5. Use the write method in the OutputStream object of the network byte output stream to upload the read file to the server
            os.write(bytes,0,len);
        }

        /*
            Solution: after uploading the file, write an end mark to the server
            void shutdownOutput() Disable the output stream for this socket.
            For TCP sockets, any previously written data will be sent, followed by TCP's normal connection termination sequence.
         */
        socket.shutdownOutput();

        //6. Use the method getInputStream in Socket to obtain the InputStream object of network byte input stream
        InputStream is = socket.getInputStream();

        System.out.println("333333333333333333333");

        //7. Use the read method in the InputStream object of the network byte input stream to read the data written back by the service
        while((len = is.read(bytes))!=-1){
            System.out.println(new String(bytes,0,len));
        }

        System.out.println("444444444444444444  while The loop cannot be printed");

        //8. Release resources (FileInputStream,Socket)
        fis.close();
        socket.close();
    }
}

3. Server side of file upload case

package com.itheima.demo02.FileUpload;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/*
    File upload case server: read the file uploaded by the client, save it to the hard disk of the server, and write back "upload succeeded" to the client

    to make clear:
        Data source: files uploaded by the client
        Destination: server's hard disk D: \ \ upload \ \ 1 jpg

    Implementation steps:
        1.Create a server ServerSocket object and the port number to be specified by the system
        2.Use the method accept in the ServerSocket object to obtain the requested client Socket object
        3.Use the method getInputStream in the Socket object to obtain the network byte input stream InputStream object
        4.Judge whether the d:\upload folder exists. If it does not exist, create it
        5.Create a local byte output stream FileOutputStream object and bind the destination to be output in the construction method
        6.Use the read method in the InputStream object of the network byte input stream to read the file uploaded by the client
        7.Use the write method in the FileOutputStream object of the local byte output stream to save the read file to the hard disk of the server
        8.Use the method getOutputStream in the Socket object to obtain the network byte output stream OutputStream object
        9.Use the write method in the OutputStream object of the network byte output stream to write back "upload succeeded" to the client
        10.Release resources (FileOutputStream,Socket,ServerSocket)
 */
public class TCPServer {
    public static void main(String[] args) throws IOException {
        //1. Create a server ServerSocket object and the port number to be specified by the system
        ServerSocket server = new ServerSocket(8888);
        //2. Use the method accept in the ServerSocket object to obtain the requested client Socket object
        Socket socket = server.accept();
        //3. Use the method getInputStream in the Socket object to obtain the network byte input stream InputStream object
        InputStream is = socket.getInputStream();
        //4. Judge whether the d:\upload folder exists. If it does not exist, create it
        File file =  new File("d:\\upload");
        if(!file.exists()){
            file.mkdirs();
        }


        //5. Create a local byte output stream FileOutputStream object and bind the destination to be output in the construction method
        FileOutputStream fos = new FileOutputStream(file+"\\1.jpg");
        //6. Use the read method in the InputStream object of the network byte input stream to read the file uploaded by the client

        System.out.println("11111111111111111111");

        int len =0;
        byte[] bytes = new byte[1024];
        while((len = is.read(bytes))!=-1){
            //7. Use the write method in the FileOutputStream object of the local byte output stream to save the read file to the hard disk of the server
            fos.write(bytes,0,len);
        }

        System.out.println("22222222222222222222222  while The loop cannot be printed");

        //8. Use the method getOutputStream in the Socket object to obtain the network byte output stream OutputStream object
        //9. Use the write method in the OutputStream object of the network byte output stream to write back "upload succeeded" to the client
        socket.getOutputStream().write("Upload successful".getBytes());
        //10. Release resources (FileOutputStream,Socket,ServerSocket)
        fos.close();
        socket.close();
        server.close();
    }
}

4. File upload case blocking

5. File upload case optimization (File Naming & circular receiving & multithreading to improve efficiency)

package com.itheima.demo03.FileUpload;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/*
    The client of the file upload case: read the local file, upload it to the server, and read the data written back by the server

    to make clear:
        Data source: C: \ \ 1 jpg
        Destination: Server

    Implementation steps:
        1.Create a local byte input stream FileInputStream object and bind the data source to be read in the construction method
        2.Create a client Socket object and bind the IP address and port number of the server in the construction method
        3.Use the method getOutputStream in the Socket to obtain the network byte output stream OutputStream object
        4.Use the read method in the FileInputStream object of the local byte input stream to read the local file
        5.Use the write method in the OutputStream object of the network byte output stream to upload the read file to the server
        6.Use the method getInputStream in Socket to obtain the InputStream object of network byte input stream
        7.Use the read method in the InputStream object of the network byte input stream to read the data written back by the service
        8.Release resources (FileInputStream,Socket)
 */
public class TCPClient {
    public static void main(String[] args) throws IOException {
        //1. Create a local byte input stream FileInputStream object and bind the data source to be read in the construction method
        FileInputStream fis = new FileInputStream("c:\\1.jpg");
        //2. Create a client Socket object and bind the IP address and port number of the server in the construction method
        Socket socket = new Socket("127.0.0.1",8888);
        //3. Use the method getOutputStream in the Socket to obtain the network byte output stream OutputStream object
        OutputStream os = socket.getOutputStream();
        //4. Use the read method in the FileInputStream object of the local byte input stream to read the local file
        int len = 0;
        byte[] bytes = new byte[1024];
        while((len = fis.read(bytes))!=-1){
            //5. Use the write method in the OutputStream object of the network byte output stream to upload the read file to the server
            os.write(bytes,0,len);
        }

        /*
            Solution: after uploading the file, write an end mark to the server
            void shutdownOutput() Disable the output stream for this socket.
            For TCP sockets, any previously written data will be sent, followed by TCP's normal connection termination sequence.
         */
        socket.shutdownOutput();

        //6. Use the method getInputStream in Socket to obtain the InputStream object of network byte input stream
        InputStream is = socket.getInputStream();



        //7. Use the read method in the InputStream object of the network byte input stream to read the data written back by the service
        while((len = is.read(bytes))!=-1){
            System.out.println(new String(bytes,0,len));
        }


        //8. Release resources (FileInputStream,Socket)
        fis.close();
        socket.close();
    }
}

package com.itheima.demo03.FileUpload;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;

/*
    File upload case server: read the file uploaded by the client, save it to the hard disk of the server, and write back "upload succeeded" to the client

    to make clear:
        Data source: files uploaded by the client
        Destination: server's hard disk D: \ \ upload \ \ 1 jpg

    Implementation steps:
        1.Create a server ServerSocket object and the port number to be specified by the system
        2.Use the method accept in the ServerSocket object to obtain the requested client Socket object
        3.Use the method getInputStream in the Socket object to obtain the network byte input stream InputStream object
        4.Judge whether the d:\upload folder exists. If it does not exist, create it
        5.Create a local byte output stream FileOutputStream object and bind the destination to be output in the construction method
        6.Use the read method in the InputStream object of the network byte input stream to read the file uploaded by the client
        7.Use the write method in the FileOutputStream object of the local byte output stream to save the read file to the hard disk of the server
        8.Use the method getOutputStream in the Socket object to obtain the network byte output stream OutputStream object
        9.Use the write method in the OutputStream object of the network byte output stream to write back "upload succeeded" to the client
        10.Release resources (FileOutputStream,Socket,ServerSocket)
 */
public class TCPServer {
    public static void main(String[] args) throws IOException {
        //1. Create a server ServerSocket object and the port number to be specified by the system
        ServerSocket server = new ServerSocket(8888);
        //2. Use the method accept in the ServerSocket object to obtain the requested client Socket object

        /*
            Keep the server listening (dead loop accept method)
            When a client uploads a file, it saves a file
         */
        while(true){
            Socket socket = server.accept();

            /*
                Use multithreading technology to improve the efficiency of the program
                When a client uploads a file, it starts a thread to complete the file upload
             */
            new Thread(new Runnable() {
                //Complete file upload
                @Override
                public void run() {
                   try {
                       //3. Use the method getInputStream in the Socket object to obtain the network byte input stream InputStream object
                       InputStream is = socket.getInputStream();
                       //4. Judge whether the d:\upload folder exists. If it does not exist, create it
                       File file =  new File("d:\\upload");
                       if(!file.exists()){
                           file.mkdirs();
                       }

                    /*
                        Customize the naming rules of a file: prevent files with the same name from being overwritten
                        Rule: domain name + millisecond value + random number
                     */
                       String fileName = "itcast"+System.currentTimeMillis()+new Random().nextInt(999999)+".jpg";

                       //5. Create a local byte output stream FileOutputStream object and bind the destination to be output in the construction method
                       //FileOutputStream fos = new FileOutputStream(file+"\\1.jpg");
                       FileOutputStream fos = new FileOutputStream(file+"\\"+fileName);
                       //6. Use the read method in the InputStream object of the network byte input stream to read the file uploaded by the client


                       int len =0;
                       byte[] bytes = new byte[1024];
                       while((len = is.read(bytes))!=-1){
                           //7. Use the write method in the FileOutputStream object of the local byte output stream to save the read file to the hard disk of the server
                           fos.write(bytes,0,len);
                       }


                       //8. Use the method getOutputStream in the Socket object to obtain the network byte output stream OutputStream object
                       //9. Use the write method in the OutputStream object of the network byte output stream to write back "upload succeeded" to the client
                       socket.getOutputStream().write("Upload successful".getBytes());
                       //10. Release resources (FileOutputStream,Socket,ServerSocket)
                       fos.close();
                       socket.close();
                   }catch (IOException e){
                       System.out.println(e);
                   }
                }
            }).start();


        }

        //The server doesn't have to be shut down
        //server.close();
    }
}

6. Simulate BS server analysis

7. Simulate BS server code implementation

package com.itheima.demo04.BSTCP;

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

/*
    Create BS version TCP server
 */
public class TCPServer {
    public static void main(String[] args) throws IOException {
        //Create a server ServerSocket and the port number to be specified by the system
        ServerSocket server = new ServerSocket(8080);
        //Use the accept method to get the requested client object (browser)
        Socket socket = server.accept();
        //Use the method getInputStream in the Socket object to obtain the network byte input stream InputStream object
        InputStream is = socket.getInputStream();
        //Use the method read in the InputStream object of the network byte input stream to read the request information of the client
        /*byte[] bytes = new byte[1024];
        int len = 0;
        while((len = is.read(bytes))!=-1){
            System.out.println(new String(bytes,0,len));
        }*/

        //Convert the is network byte input stream object into character buffer input stream
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        //Read the first line of client request information GET /11_Net/web/index.html HTTP/1.1
        String line = br.readLine();
        //Cut the read information as long as the middle part / 11_Net/web/index.html
        String[] arr = line.split(" ");
        //Remove the / in front of the path and intercept 11_Net/web/index.html
        String htmlpath = arr[1].substring(1);

        //Create a local byte input stream and bind the html path to be read in the construction method
        FileInputStream fis = new FileInputStream(htmlpath);
        //Use the method getOutputStream in the Socket to obtain the network byte output stream OutputStream object
        OutputStream os = socket.getOutputStream();

        // Write HTTP protocol response header, fixed writing method
        os.write("HTTP/1.1 200 OK\r\n".getBytes());
        os.write("Content-Type:text/html\r\n".getBytes());
        // You must write a blank line, or the browser will not parse it
        os.write("\r\n".getBytes());

        //Copy the file by reading and writing, and write back the html file read by the service to the client
        int len = 0;
        byte[] bytes = new byte[1024];
        while((len = fis.read(bytes))!=-1){
            os.write(bytes,0,len);
        }

        //Release resources
        fis.close();
        socket.close();
        server.close();
    }
}

package com.itheima.demo04.BSTCP;

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

/*
    Create BS version TCP server
 */
public class TCPServerThread {
    public static void main(String[] args) throws IOException {
        //Create a server ServerSocket and the port number to be specified by the system
        ServerSocket server = new ServerSocket(8080);

        /*
            The browser parses the html page written back by the server. If there are pictures in the page, the browser will open a separate thread to read the pictures of the server
            Let's keep the server listening. The server will write back once the client requests it
         */
        while(true){
            //Use the accept method to get the requested client object (browser)
            Socket socket = server.accept();

            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        //Use the method getInputStream in the Socket object to obtain the network byte input stream InputStream object
                        InputStream is = socket.getInputStream();
                        //Use the method read in the InputStream object of the network byte input stream to read the request information of the client
                        /*byte[] bytes = new byte[1024];
                        int len = 0;
                        while((len = is.read(bytes))!=-1){
                            System.out.println(new String(bytes,0,len));
                        }*/

                        //Convert the is network byte input stream object into character buffer input stream
                        BufferedReader br = new BufferedReader(new InputStreamReader(is));
                        //Read the first line of client request information GET /11_Net/web/index.html HTTP/1.1
                        String line = br.readLine();
                        System.out.println(line);
                        //Cut the read information as long as the middle part / 11_Net/web/index.html
                        String[] arr = line.split(" ");
                        //Remove the / in front of the path and intercept 11_Net/web/index.html
                        String htmlpath = arr[1].substring(1);

                        //Create a local byte input stream and bind the html path to be read in the construction method
                        FileInputStream fis = new FileInputStream(htmlpath);
                        //Use the method getOutputStream in the Socket to obtain the network byte output stream OutputStream object
                        OutputStream os = socket.getOutputStream();

                        // Write HTTP protocol response header, fixed writing method
                        os.write("HTTP/1.1 200 OK\r\n".getBytes());
                        os.write("Content-Type:text/html\r\n".getBytes());
                        // You must write a blank line, or the browser will not parse it
                        os.write("\r\n".getBytes());

                        //Copy the file by reading and writing, and write back the html file read by the service to the client
                        int len = 0;
                        byte[] bytes = new byte[1024];
                        while((len = fis.read(bytes))!=-1){
                            os.write(bytes,0,len);
                        }

                        //Release resources
                        fis.close();
                        socket.close();
                    }catch (IOException e){
                        e.printStackTrace();
                    }
                }
            }).start();


        }


        //server.close();
    }
}

Keywords: Java

Added by bobthedog on Mon, 07 Feb 2022 05:32:00 +0200