java network programming and Throw exception

Exception

What is an exception (Exception in the narrow sense can be handled)

Abnormal system

Throwable

Error

Exception

? Runtime exception

?Compile time exception

Exception handling

try

catch

finally

throws

throw

Custom exception





throws: After the method parameter list, it is used to declare that this method may have an exception, and whoever calls it handles it. Note that runtime exceptions will not be automatically prompted, but check exceptions will be automatically prompted.

The throw keyword is used to display an exception. In the method body, when a certain condition is not met, an exception object is actively thrown, and the program will no longer execute backwards.

Custom exceptions: The standard exception classes defined in the Java API are all related to syntax (such as index out of bounds, null pointer), but when our program may not meet certain business conditions, we want to handle it by throwing an exception. At this time, you need to customize a business-related exception class to represent it (for example, if the score is illegal, provide ScoreException)

Example:

package exception;

import java.util.Hashtable;

//Exception handling (throw)
public class ThrowText {<!-- -->
    public static void main(String[] args) {<!-- -->
        try {<!-- -->
            char res = checkscore(110);
            System.out.println(res);
        } catch(Exception e){<!-- -->
            e.printStackTrace();
            System.out.println(e.getMessage());
        }

        //new Hashtable<>().put(null,null);
        //"aa".charAt(1);

    }
    public static char checkscore(int score) throws Exception {<!-- -->
        if(score < 0 || score >100){<!-- -->
            throw new Exception("Illegal score"); //When the program does not meet certain conditions, an exception object is actively thrown, and the program cannot continue to execute.
        }
        else if(score >= 90){<!-- -->
            return 'A';
        }
        else if(score >= 80){<!-- -->
            return 'B';
        }
        else{<!-- -->
            return 'C';
        }
    }
}

package exception;

//custom exception
public class ThrowText2 {<!-- -->
    public static void main(String[] args) {<!-- -->
        try {<!-- -->
            char res = checkscore(110);
            System.out.println(res);
        } catch(ScoreException e){<!-- -->
            e.printStackTrace();
            System.out.println(e.getMessage());
        }

        //new Hashtable<>().put(null,null);
        //"aa".charAt(1);

    }
    public static char checkscore(int score) throws ScoreException{<!-- -->
        if(score < 0 || score >100){<!-- -->
            throw new ScoreException("The score is illegal"); //When the program does not meet certain conditions, an exception object is actively thrown, and the program cannot continue to execute.
        }
        else if(score >= 90){<!-- -->
            return 'A';
        }
        else if(score >= 80){<!-- -->
            return 'B';
        }
        else{<!-- -->
            return 'C';
        }
    }
}

package exception;

public class ScoreException extends Exception{<!-- -->
    public ScoreException() {<!-- -->
    }

    public ScoreException(String message) {<!-- -->
        super(message);
    }
}

Network programming

Network Programming Overview

What is a computer network
   Connect computers in different areas through communication equipment and lines
   Next, realize the system of data transmission and sharing.
   To realize the connection between different computers, there must be a media connection.
   
What is network programming?
  (With the help of computer network, the written program can be realized and data can be transferred on different computers)
   Chat--->Chat software
   The Java language supports data transmission between networks. It encapsulates the underlying details and provides programmers with a set of standard class libraries, making it easy to use Java language to develop software that can communicate over the network.

Core issues in network programming
   How to find the target host in the network world, and the target software
   (win + r cmd ipconfig to check the IP of your computer)
   How to carry out data transmission safely and reliably (protocol, i.e. rules)

Some basic knowledge of the Internet

Network model
  OSI reference model is an idealized standard model
     Divided into 7 layers
  Practical use: Tcp/ip network model
     Divided into 4 layers
       Application layer (http)
       Transport layer (protocol)
       Network layer (IP)
       Physical layer (hardware device)
  Why should network transmission data be layered?
     In different layers, add different headers (protocol, IP) to the data, and divide the work layer by layer.

Network communication elements (IP: find the host; Port: find the program; protocol)
   Target host, target software (IP + port)
     IP: In the online world, the address of a computer
         LAN address, connect to the router, the IP will be automatically assigned
         WAN address, home broadband, connection to the outside world
         Local address, local loopback address (127.0.0.1)
     Port: It is the number of the program running in the computer, corresponding to the program
       Port number: between 0-65535, but because 0-1024 is used by some system programs, the program developed by myself is between 1024-65535, but it cannot conflict with the existing port
     Communication Protocols: How to Transfer Protocols Securely
       In order to carry out data transmission safely and reliably, it is necessary to control the transmission content, speed, error handling, etc., and formulate some regulations.

Two main protocols at the transport layer:

TCP (Transmission Control Protocol)
    Before using the TCP protocol for data transmission, you must first check whether the network is smooth and whether the client can connect to the server. If it can connect, the data will be transmitted. If the connection cannot be made, an error will be reported.
    The connection uses a three-way handshake mechanism
    Is reliable and less efficient than UDP
    Disconnect using a four-way handshake mechanism
       
UDP (User Datagram Protocol)
    Encapsulate the data into datagrams. The datagram includes the data source (own computer IP) and target (receiving end IP port). There is no need to establish a connection before sending. Just send it. You don’t know whether it will succeed or not. It is unsafe, but efficient

Example:

import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class ServerPro {<!-- -->
    public static void main(String[] args) {<!-- -->
        try {<!-- -->
            ServerSocket serverSocket = new ServerSocket(9999);

            Socket socket = serverSocket.accept(); //Listen to see if a client is connected to the server. When listening, the program will be blocked.

            while(true){<!-- -->
                //Accept client information
                InputStream inputStream = socket.getInputStream();
                DataInputStream dataInputStream = new DataInputStream(inputStream);
                String s = dataInputStream.readUTF();
                System.out.println("Client said:" + s);

                //Send message back to client
                OutputStream outputStream = socket.getOutputStream();
                DataOutputStream dataOutputStream = new DataOutputStream(outputStream); //Data stream processing, output string

                Scanner scanner = new Scanner(System.in);
                System.out.println("Server input:");
                String s1 = scanner.next();

                dataOutputStream.writeUTF(s1);
            }

        } catch (IOException e) {<!-- -->
            e.printStackTrace();
            System.out.println("Server startup failed, port is occupied");
        }
    }
}

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

public class ClientPro {<!-- -->
    public static void main(String[] args) {<!-- -->
        //Create client
        try {<!-- -->
            Socket socket = new Socket("127.0.0.1",9999);

            while(true){<!-- -->
                //Send information to the server
                OutputStream outputStream = socket.getOutputStream();
                DataOutputStream dataOutputStream = new DataOutputStream(outputStream); //Data stream processing, output string

                Scanner scanner = new Scanner(System.in);
                System.out.println("Client input:");
                String s = scanner.next();

                dataOutputStream.writeUTF(s);

                //Accept messages from the server
                InputStream inputStream = socket.getInputStream();
                DataInputStream dataInputStream = new DataInputStream(inputStream);
                String s1 = dataInputStream.readUTF();
                System.out.println("The server said:" + s1);
            }

        } catch (IOException e) {<!-- -->
            e.printStackTrace();
        }
    }
}