[learning notes] network programming

Posted by lopes_andre on Tue, 08 Mar 2022 09:47:13 +0100

1. Introduction to network programming

link

1.1 what is a computer network?

packet
What is a TCP connection? phone
What is a UDP connection? send emails
What is computer network? It refers to a computer system that connects multiple computers and their external devices with independent functions in different geographical locations through communication lines and realizes resource sharing and information transmission under the management and coordination of network operating system, network management software and network communication protocol.
What is the purpose of network programming? Data exchange, communication,
What does it take to achieve this effect?

  1. How to accurately locate a host on the network? 192.168.16.124: port to locate a resource on this computer
  2. After finding the host, how to transmit data?

javaWeb: Web programming B/S architecture
Network programming: TCP/IP C/S architecture

1.2 two elements of network communication

How to realize network communication?
Address of both parties:

  • ip
  • Port number
  • 192.168.16.124: 5900

Rules: network communication protocols: http (Hypertext Transfer Protocol), ftp,smtp,tcp,udp, etc
TCP/IP reference model: OSI layer 7 reference

1.3. IP address

IP address: InetAddress

  • Uniquely locate a computer on a network

  • 127.0.0.1 represents the local localhost

  • Classification of IP addresses

    • Public network (Internet) / private network (LAN)
      • 192.168.xx.xx LAN
      • ABCD class of IP address
    • IPV4 / IPV6
      • ipv4: 127.0.0.1, composed of 4 bytes, 0 ~ 255, 4.2 billion
      • ipv6: 2001:0bb2:aaaa:0000:0000:abad:1312:1245128 bits, 8 unsigned integers
  • Domain name: memory IP problem

package javanet.lesson;

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

//Test IP
public class TestInetAddress {
    public static void main(String[] args) {
        try {
            // Query local address
            InetAddress inetAddress1 = InetAddress.getByName("127.0.0.1");
            System.out.println(inetAddress1);
            InetAddress inetAddress2 = InetAddress.getByName("localhost");
            System.out.println(inetAddress2);
            InetAddress inetAddress3 = InetAddress.getLocalHost();
            System.out.println(inetAddress3);
            // Query network ip address
            InetAddress inetAddress4 = InetAddress.getByName("www.baidu.com");
            System.out.println(inetAddress4);

            // common method
            System.out.println(inetAddress4.getAddress());
            System.out.println(inetAddress4.getCanonicalHostName()); // Canonical name
            System.out.println(inetAddress4.getHostAddress()); // ip
            System.out.println(inetAddress4.getHostName()); // Domain name, or your own name
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

    }
}

1.4. Port number

A port represents the progress of a program on a computer

  • Different processes have different port numbers! Used to distinguish software
  • Specified 0 ~ 65535
  • It is divided into TCP port and UDP port: 65535 * 2, tcp80 and udp80. Port numbers cannot conflict under a single protocol
  • Port classification
    • Public port 0 ~ 1023
      • HTTP : 80
      • HTTPS: 443
      • FTP: 21
      • Telent: 23
    • Program registration port: 1024 ~ 49151, assign users or programs
      • Tomcat: 8080
      • MySQL: 3306
      • Oracle: 1521
  • Dynamic port, private port: 49152 ~ 65535
netstat -ano # View all ports
netstat -ano|findstr "5900"  # View the specified port
tasklist|findstr "8696"   #  View the process of the specified port
package javanet.lesson;

import java.net.InetSocketAddress;

public class TestInetSocketAddress {
    public static void main(String[] args) {
        InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1",8080);
        InetSocketAddress inetSocketAddress1 = new InetSocketAddress("localhost",8080);
        System.out.println(inetSocketAddress);
        System.out.println(inetSocketAddress1);
        System.out.println(inetSocketAddress.getAddress());
        System.out.println(inetSocketAddress.getHostName()); // address
        System.out.println(inetSocketAddress.getPort()); // port
    }
}

1.5. communication protocol

Agreement: agreement, just like Mandarin.
Network communication protocol: rate, transmission code rate, code structure, transmission control
The principle of making big things small: the concept of stratification

TCP/IP protocol cluster: it is actually a group of protocols

important:
TCP: user transport protocol
UDP: User Datagram Protocol
Famous agreement:
IP: network interconnection protocol
TCP

TCP UDP comparison
TCP: call

  • Connection, stable
  • Three handshakes and four waves
    (initiate response, then respond, connect) at least three times to ensure a stable connection
    (A: I'm going to disconnect B: I know you're going to disconnect a: you're really going to disconnect B: I'm really going to disconnect)
  • Client, server
  • The transmission is completed, the connection is released, and the efficiency is low

UDP: send SMS

  • Not connected, unstable
  • Client and server: there is no clear boundary
  • It can be sent to you whether prepared or not
  • DDOS: flood attack and saturation attack

1.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.

1.2 network communication protocol

Network communication protocol: multiple computers can be connected through computer network. Computers located in the same network need to abide by certain rules when connecting and communicating, just as cars driving on the road must abide by traffic rules. In the computer network, these rules of connection and communication are called network communication protocol. It makes unified provisions on the transmission format, transmission rate and transmission steps of data. Both sides of communication must abide by them at the same time to 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.

1.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:

  • UDP: User Datagram Protocol. UDP is a connectionless communication protocol, that is, during data transmission, the sender and receiver of data do not establish a logical connection. In short, when a computer sends data to another computer, the sender will send data without confirming whether the receiver exists. Similarly, when the receiver receives the data, it will not feed back whether it has received the data to the sender.
    Due to the low resource consumption and high communication efficiency of using UDP protocol, it is usually used for the transmission of audio, video and ordinary data. For example, video conference uses UDP protocol, because even if one or two packets are lost occasionally, it will not have a great impact on the receiving result.
    However, when using UDP protocol to transmit data, due to the non connectivity of UDP, the integrity of data cannot be guaranteed. Therefore, it is not recommended to use UDP protocol when transmitting important data. The UDP exchange process is shown in the figure below.

    Features: the data is limited to 64kb, beyond which it cannot be sent.
    Datagram: the basic unit of network transmission

  • TCP: Transmission Control Protocol. TCP protocol is a connection oriented communication protocol, that is, before transmitting data, establish a logical connection between the sending end and the receiving end, and then transmit data. It provides reliable and error free data transmission between two computers. In TCP connection, the client and server must be specified. The client sends a connection request to the server. Each connection creation needs to go through "three handshakes".

    • Three handshakes: in TCP protocol, three interactions between the client and the server in the preparation stage of sending data to ensure the reliability of the connection.
      • For 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 back a response to the client to notify the client that it has received the connection request.
      • For the third handshake, the client sends confirmation information to the server again to confirm the connection. The whole interaction process is shown in the figure below.
        After three handshakes are completed and the connection is established, the client and server can start data transmission. Because of this connection oriented feature, TCP protocol can ensure the security of data transmission, so it is widely used, such as downloading files, browsing web pages and so on.

2. TCP communication protocol

2.1 general

TCP communication can realize the data interaction between two computers. The two ends of communication should be strictly divided into Client and Server.
Steps for communication between two ends:
1. The server program needs to be started in advance and wait for the connection of the client.
2. The client actively connects to the server. Only after the connection is successful can the communication be realized. The server cannot actively connect to the client.

In Java, two classes are provided to implement TCP communication programs:

  1. Client: Java net. The Socket class represents. Create a Socket object, send a connection request to the server, and the server responds to the request. The two establish a connection and start communication.
  2. Server: Java net. The ServerSocket class represents. Creating a ServerSocket object is equivalent to starting a service and waiting for the client to connect.

2.2 implementation of TCP communication client code

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: contains IP Network unit of 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:  Represents the name of the server host/ Server IP address
        int port : Represents the port number of the server
 Member method:
        OutputStream getOutputStream()   Returns an output stream that is larger than the socket.
        InputStream getInputStream()   Returns an input stream that is larger than the socket.
        void close()Close this socket.
Implementation steps:
    1.Create a client object Socket,Constructor binding server IP Address and port number
    2.use socket Ten thousand methods in object getoutputstream()Take network byte output stream outputstream object
    3.Use network byte output stream outputstream Methods in objects write,Send data to server
    4.use Socket Methods in objects getInputstream()Get network byte input stream Inputstream object
    5.Use network byte input stream Inputstream Methods in objects read,Read the data written back by the server
    6.Release 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 Java. Net will be thrown net. ConnectException
If the server is started, you can interact

package javanet.lesson;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/*
     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:  Represents the name of the server host / the IP address of the server
            int port : Represents the port number of the server
     Member method:
            OutputStream getOutputStream()   Returns an output stream that is larger than the socket.
            InputStream getInputStream()   Returns an input stream that is larger than the 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 ten thousand method getoutputstream() in the socket object to get the network byte output stream outputstream object
        3.Use the method write 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 Java. Net will be thrown net. ConnectException
            If the server is started, you can interact
 */
public class TCPClient {
    public static void main(String[] args) throws Exception{
        // 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 ten thousand method getoutputstream() in the socket object to get the network byte output stream outputstream object
        OutputStream outputStream = socket.getOutputStream();
        //  3. Use the write method in the outputstream object of the network byte output stream to send data to the server
        outputStream.write("Hello server".getBytes(StandardCharsets.UTF_8));

//        4. Use the method getInputstream() in the Socket object to obtain the network byte input stream Inputstream object
        InputStream inputStream = 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 = inputStream.read(bytes);
        System.out.println(new String(bytes,0, len));
            //        6. Release resources (Socket)
        socket.close();

    }
}

2.3 code implementation of TCP communication server

Server side of TCP communication: accept the request of 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

   One thing must be clear on the server side,You must know which client requested the server
   All available accept Method to get the requested client object Socket

   Member method:
           Socket accept();   Listen and accept connections from this socket.

    Server implementation steps:
       1. Create server ServerSocket Object and system to specify the port number
       2. use ServerSocket Methods in objects accept,Gets the requested client object Socket
       3. use Socket Methods in objects getInputstream()Get stream input network bytes Inputstream object
       4. Use network byte input stream Inputstream Methods in objects read,Read the data sent by the client
       5. use socket Ten thousand methods in object getoutputstream()Take network byte output stream outputstream object
       6. Use network byte output stream outputstream Methods in objects write,Write back data to the client
       7. Release resources( Socket,ServetSocket)
package javanet.lesson;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * TCP Server side of communication: accept the request of 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
 *      All the Socket objects of the requested client can be obtained by using the accept method
 *
 *      Member method:
 *              Socket accept();   Listen and accept connections from this socket.
 *
 *       Server implementation steps:
 *          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 ten thousand method getoutputstream() in the socket object to get 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 serverSocket = new ServerSocket(8888);
        // 2. Use the method accept in the ServerSocket object to obtain the requested client object Socket
        Socket socket = serverSocket.accept();
        //3. Use the method getInputstream() in the Socket object to obtain the network byte input stream Inputstream object
        InputStream inputStream = 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 = inputStream.read(bytes);
        System.out.println(new String(bytes,0, len));
        //5. Use the ten thousand method getoutputstream() in the socket object to get the network byte output stream outputstream object
        OutputStream outputStream = socket.getOutputStream();
        //6. Use the write method in the outputstream object of the network byte output stream to write back data to the client
        outputStream.write("Yes, thank you".getBytes(StandardCharsets.UTF_8));
        //7. Release resources (Socket, ServerSocket)
        socket.close();
        serverSocket.close();
    }

}

3. Comprehensive case: file upload case

3.1 demand analysis

3.2 client of file upload case

package javanet.lesson;

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

/*
    File uploaded to the client, data written back to 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 getOutputStream in the Socket method 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 write in the network byte output stream OutputStream object method to upload the read file to the server
            6. Use the method getInputStream in the Socket to narrow the network byte input stream InputStream object
            7. Use the read method of the input stream in the network object to read back the data in the network stream
            8. Release resources (FileInputstream,Socket)

 */
public class TCPUPload {
    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 fileInputStream = new FileInputStream("d:\\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 getOutputStream in the Socket method to obtain the network byte output stream OutputStream object
        OutputStream outputStream = 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 = fileInputStream.read(bytes)) != -1){
            //5. Use write in the network byte output stream OutputStream object method to upload the read file to the server
            outputStream.write(bytes,0,len);

        }
        /*
           Solution: the solution: upload the completed file and write an end tag 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 the Socket to narrow the network byte input stream InputStream object
        InputStream inputStream = 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 = inputStream.read(bytes)) != -1){
            System.out.println(new String(bytes,0,len));
        }
        //8. Release resources (FileInputstream,Socket)
        fileInputStream.close();
        socket.close();
    }
}

3.2 server of file upload case

package javanet.lesson;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/*
Server side of file upload case: read the file uploaded by the client, save it to the hard disk of the server, and "write back" to the client to upload it successfully“

        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 get the network byte output stream OutputStream object
            9. Use the write method in the OutputStream object of the network byte input stream to upload "write back" to the client successfully“
            10. Release resources (ServerSocket, Socket, FileOutputStream)
 */
public class TCPUpServer {
    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 serverSocket = new ServerSocket(8888);
        //2. Use the method accept in the ServerSocket object to obtain the requested client Socket object
        Socket socket = serverSocket.accept();
        //3. Use the method getInputStream in the socket object to obtain the network byte input stream InputStream object
        InputStream inputStream = 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.mkdir();
        }
        //5. Create a local byte output stream FileOutputStream object, and bind the destination to be output in the construction method
        FileOutputStream fileOutputStream = 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("111111111111111111111111111111111");
        int count = 0;
        byte[] bytes = new byte[1024];
        while ((count = inputStream.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
            fileOutputStream.write(bytes,0,count);
        }
        System.out.println("222222222222222 while Dead cycle");

        //8. Use the method getOutputStream in the Socket object to get the network byte output stream OutputStream object
        OutputStream outputStream = socket.getOutputStream();
        //9. Use the write method in the OutputStream object of the network byte input stream to "write back" to the client and upload successfully“
        outputStream.write("Upload successful".getBytes(StandardCharsets.UTF_8));
        //10. Release resources (ServerSocket, Socket, FileOutputStream)
        serverSocket.close();
        socket.close();
        fileOutputStream.close();
    }
}

3.3 file upload blocking

I didn't encounter this problem
Because when the first while judgment of the client is - 1, the cycle is stopped directly. - 1 has not been written to the server from the beginning

Solution: upload the completed file and write an end mark to the server

3.4 file upload case optimization

  1. Customize the naming rules of a file: prevent files with the same name from being overwritten
  2. Keep the server listening ()
  3. Use multithreading technology to improve the efficiency of the program. When a client uploads a file, start the thread to complete the file upload
package javanet.lesson;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Random;

/*
Server side of file upload case: read the file uploaded by the client, save it to the hard disk of the server, and "write back" to the client to upload it successfully“

        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 get the network byte output stream OutputStream object
            9. Use the write method in the OutputStream object of the network byte input stream to upload "write back" to the client successfully“
            10. Release resources (ServerSocket, Socket, FileOutputStream)
 */
public class TCPUpServer {
    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 serverSocket = 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 = serverSocket.accept();

            /*
                    Use multithreading technology to improve the efficiency of the program
                    When a client uploads a file, it starts the 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 inputStream = 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.mkdir();
                        }

                    /*
                            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 = "iscast" + 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 fileOutputStream = new FileOutputStream(file+"\\1.jpg");
                        FileOutputStream fileOutputStream = 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 count = 0;
                        byte[] bytes = new byte[1024];
                        while ((count = inputStream.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
                            fileOutputStream.write(bytes,0,count);
                        }

                        //8. Use the method getOutputStream in the Socket object to get the network byte output stream OutputStream object
                        OutputStream outputStream = socket.getOutputStream();
                        //9. Use the write method in the OutputStream object of the network byte input stream to "write back" to the client and upload successfully“
                        outputStream.write("Upload successful".getBytes(StandardCharsets.UTF_8));
                        //10. Release resources (ServerSocket, Socket, FileOutputStream)

                        socket.close();
                        fileOutputStream.close();
                    }catch (IOException e){
                        System.out.println(e);
                    }
                }
            }).start();


        }
        //serverSocket.close();
    }
}

package javanet.lesson;

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

/*
    File uploaded to the client, data written back to 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 getOutputStream in the Socket method 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 write in the network byte output stream OutputStream object method to upload the read file to the server
            6. Use the method getInputStream in the Socket to narrow the network byte input stream InputStream object
            7. Use the read method of the input stream in the network object to read back the data in the network stream
            8. Release resources (FileInputstream,Socket)

 */
public class TCPUPload {
    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 fileInputStream = new FileInputStream("d:\\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 getOutputStream in the Socket method to obtain the network byte output stream OutputStream object
        OutputStream outputStream = 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 = fileInputStream.read(bytes)) != -1){
            //5. Use write in the network byte output stream OutputStream object method to upload the read file to the server
            outputStream.write(bytes,0,len);

        }
        /*
           Solution: the solution: upload the completed file and write an end tag 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 the Socket to narrow the network byte input stream InputStream object
        InputStream inputStream = 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 = inputStream.read(bytes)) != -1){
            System.out.println(new String(bytes,0,len));
        }
        //8. Release resources (FileInputstream,Socket)
        fileInputStream.close();
        socket.close();
    }
}

4. Simulate BS server

Watch the video first

Thinking summary:

1. What does it mean to shake hands three times and wave hands four times?

profound understanding
video
Three handshakes:

Why three handshakes instead of two?
The server establishes the connection after replying to AYN+ACK, which is to prevent errors caused by the sudden transmission of invalid request messages to the server
Solve the problem of unreliable network channel

How to solve the problem of packet loss?
How to solve the disorder problem?

Four waves

Topics: Java Data Analysis