Day 28 of learning big data - UDP, TCP transmission, classloader, reflection and dynamic proxy

Posted by zarp on Sat, 26 Feb 2022 15:23:27 +0100

UDP transport

1: Establish udp socket service
2: Receive data through receive method
3: Store the received data in the packet object
4: Analyze the received data through the function of packet object
5: Resources can be closed

client
/*
        Add feedback according to our normal thinking, but there is no response. Why
        The reason is that reading a text file can use null as an end message, but it cannot end the message in this way in the channel
        So the server doesn't know that the client has finished uploading. The client is still waiting for the server to give me feedback, so there is a phenomenon of waiting for each other.

        How to solve it?
        1,Write another piece of data and tell the server that reading this data means that the file has been uploaded. There is no data coming, so the server doesn't have to continue reading
            Although this can solve the problem, it's not good
        2,Socket Object

 */
public class UploadClient {
    public static void main(String[] args) throws Exception {
        //1. Create Socket object
        Socket s = new Socket("192.168.7.64", 12345);

        //2. Gets the local character input stream object
        BufferedReader br = new BufferedReader(new FileReader("src\\com\\shujia\\yl\\day25\\DieLockDemo.java"));

        //3. Gets the byte output stream object in the channel
        OutputStream outputStream = s.getOutputStream();
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
        BufferedWriter bw = new BufferedWriter(outputStreamWriter);

        String line = null;
        while ((line = br.readLine()) != null) {
            bw.write(line);
            bw.newLine();
            bw.flush();
        }


        //Customize an end tag
//        bw.write("over");
//        bw.newLine();
//        bw.flush();

        //Inform the server that I have no data. Don't wait
        s.shutdownOutput();


        //Gets the byte input stream object in the channel
        InputStream inputStream = s.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        BufferedReader br2 = new BufferedReader(inputStreamReader);
        String s1 = br2.readLine(); // Blocking waiting for feedback from the service
        System.out.println(s1);


        //Release resources
        br.close();
        s.close();


    }
}
Server
public class UploadServer {
    public static void main(String[] args) throws Exception {
        //1. Create a ServerSocket object on the server side
        ServerSocket ss = new ServerSocket(12345);

        //2. Listen to the connection between the client and it and get the corresponding Socket object
        Socket s = ss.accept();

        //3. Gets the byte input stream object in the channel
        InputStream inputStream = s.getInputStream();
        InputStreamReader isr = new InputStreamReader(inputStream);
        BufferedReader br = new BufferedReader(isr);

        //4. Create a normal character output stream object
        BufferedWriter bw = new BufferedWriter(new FileWriter("netFile.txt"));

        String line = null;
        while ((line=br.readLine())!=null){
//            if("over".equals(line)){
//                break;
//            }
            bw.write(line);
            bw.newLine();
            bw.flush();
        }

        //The server gives feedback
        //Gets the byte output stream object in the channel
        OutputStream outputStream = s.getOutputStream();
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
        BufferedWriter bw2 = new BufferedWriter(outputStreamWriter);
        bw2.write("File uploaded successfully");
        bw2.newLine();
        bw2.flush();

        //Release resources
        bw.close();
        s.close();



    }
}

TCP transmission

Socket and ServerSocket
Establish client and server
After the connection is established, the data is transmitted through the IO stream in the Socket
Close socket
Similarly, the client and server are two separate applications.

Class loader and reflection

reflex

Reflection: use a Class file object to change the member variables, construction methods and member methods in the file object

class:
Member variable: Field
Construction method: Constructor
Member Method: Method

How to get the Class file object corresponding to a Class?
1. Return the runtime class of this Object through the getClass() method in the Object class
2. Without the new object, get the class file object of the class and use the static attribute class of the class to get it

public class ReflexDemo1 {
    public static void main(String[] args) {
        //Method 1: return the runtime class of this Object through the getClass() method in the Object class
        Person p = new Person();
        Class<? extends Person> c1 = p.getClass();
        Person p2 = new Person();
        Class<? extends Person> c2 = p.getClass();
        System.out.println(c1==c2);

        //Method 2: get the class file object of this class without the new object, and use the static attribute class of the class to get it
        Class<Person> c3 = Person.class;
        System.out.println(c1==c3);
        System.out.println(c2==c3);

        //Method 3: public static class <? > forName(String className)
        //Returns the class object associated with the class or interface of the given string name. Calling this method is equivalent to:
        try {
            Class<?> c4 = Class.forName("com.shujia.wyh.day27.Person");
            System.out.println(c1==c4);
            System.out.println(c2==c4);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }



    }
}

How to obtain and use the constructor in the Class file object through reflection?

public class ReflexDemo2 {
    public static void main(String[] args) throws Exception {
        //Get Class file object
        Class<?> c1 = Class.forName("com.shujia.wyh.day27.Person");

        //Get construction methods. You can only get all public construction methods
        //public Constructor<?>[] getConstructors()
        //Returns an array containing the Constructor object,
        Constructor<?>[] cons = c1.getConstructors();
        for(Constructor c : cons){
            System.out.println(c);
        }
        System.out.println("==========================================");
        //public Constructor<?>[] getDeclaredConstructors()
        //Returns an array class of all Constructor objects that reflect the class declaration represented by the Constructor object
        //Get all construction methods, including private, protected, default and public
        Constructor<?>[] cons2 = c1.getDeclaredConstructors();
        for(Constructor c: cons2){
            System.out.println(c);
        }
        System.out.println("==========================================");
        //Get a single construction method
        //Public constructor < T > getconstructor (class <? >... Parametertypes)
        //Returns a Constructor object that reflects the specified public class function of the class represented by the Constructor object.
//        Constructor<?>  con = c1. getConstructor(); // Equivalent to obtaining parameterless construction method
//        System.out.println(con);
        Constructor<?> con = c1.getConstructor(String.class);
        System.out.println(con);
//        Constructor<?> con = c1.getDeclaredConstructor(String.class, int.class);
//        System.out.println(con);
        System.out.println("===========================================");
        //public T newInstance(Object... initargs)
        //Using the Constructor represented by this Constructor object, create and initialize a new instance of the Constructor's declaration class with the specified initialization parameters.
//        Object o = con.newInstance("hello", 23);
//        System.out.println(o);
        Person p = (Person)con.newInstance("1001");
        System.out.println(p);



    }
}

Get private constructor and create object through reflection

public class ReflexDemo3 {
    public static void main(String[] args) throws Exception {
        //Gets the bytecode file object of the class
        Class<?> c1 = Class.forName("com.shujia.wyh.day27.Person");

        //Get private constructor
        Constructor<?> con = c1.getDeclaredConstructor(String.class, int.class);
        System.out.println(con);
        //IllegalAccessException illegal access exception
        //Violent visit
        con.setAccessible(true); //If the value here is true, it means that the access check of the Java language is cancelled when the reflected object is used
        //Use the methods in the Constructor class to create objects
        Object o = con.newInstance("Ming Wang", 18);
        Person p = (Person) o;
        System.out.println(p);
    }
}

Get member variables through reflection and use

public class ReflexDemo4 {
    public static void main(String[] args) throws Exception {
        //1. Get bytecode file object
        Class<?> c1 = Class.forName("com.shujia.wyh.day27.Person");

        //Get all public member variables
        //public Field[] getFields()
        //Returns all accessible public Field class objects that contain an array Field object that reflects the class or interface represented by it.
        Field[] fields = c1.getFields();
        for (Field f : fields) {
            System.out.println(f);
        }
        System.out.println("==========================================");
        //public Field[] getDeclaredFields()
        //Gets all member variables in the current class
        //The returned array Field object reflects all Field class objects declared by the class or interface represented by this.
        //This includes public, protected, default (package) access and private fields, but does not include inherited fields.
        Field[] fields2 = c1.getDeclaredFields();
        for (Field f : fields2) {
            System.out.println(f);
        }
        System.out.println("=========================================");
        //Get the parameterless construction method, and then use reflection to assign values to member variables
        Constructor<?> con = c1.getConstructor();
        //create object
        Object o = con.newInstance();
        System.out.println(o);
        System.out.println("=========================================");
        //Get single member variable
        Field id = c1.getField("id");
        //Assigns a new value to the member variable on the specified object
        //void set(Object obj, Object value)
        //Sets the Field represented by this Field object on the specified object parameter to the specified new value.
        id.set(o,"1002");
        System.out.println(o);
        System.out.println("==========================================");
        //Reflection gets private member variables and assigns values
        //NoSuchFieldException
//        Field name = c1.getField("name");
//        System.out.println(name);
        Field name = c1.getDeclaredField("name");
        System.out.println(name);
        //Violent visit
        name.setAccessible(true);
        name.set(o,"Wang Yu");
        System.out.println(o);
        System.out.println("==========================================");
        //Get the protected modified member variable without violent access
        Field address = c1.getDeclaredField("address");
        address.set(o,"Hefei, Anhui");
        System.out.println(o);
        System.out.println("==========================================");
        //Get the member variable modified by the default modifier and assign a value, without violent access
        Field age = c1.getDeclaredField("age");
        age.set(o,19);
        System.out.println(o);


    }
}

Get member methods through reflection and use

public class ReflexDemo5 {
    public static void main(String[] args) throws Exception {
        //1. Get bytecode file object
        Class<?> c1 = Class.forName("com.shujia.wyh.day27.Person");

        //Acquisition method
        //public method [] getMethods()
        //Get the public methods in this class and all public methods in the parent class
        //Returns all public method class objects that contain an array method object that reflects the class or interface represented thereby, including those declarations inherited from the class or interface and those inherited from the superclass and superinterface
        Method[] methods = c1.getMethods();
        for (Method m : methods) {
            System.out.println(m);
        }
        System.out.println("=========================================");
        Method[] methods2 = c1.getDeclaredMethods();
        //Get all your own methods, including private ones. You can't get the of the parent class
        for (Method m : methods2) {
            System.out.println(m);
        }
        System.out.println("=========================================");
        //Get a single method and call
        Method fun1 = c1.getMethod("fun1");
        Constructor<?> cons = c1.getConstructor();
        Object o = cons.newInstance();
        //public Object invoke(Object obj,Object... args)
        //Calls the base method represented by this method object on the method object with the specified parameters.
        //The first parameter refers to the object that calls the method, and the second parameter refers to the actual data (actual parameter) that needs to be passed in
        fun1.invoke(o);
        System.out.println("========================================");
//        Method fun2 = c1.getMethod("fun2", String.class);
//        System.out.println(fun2);
        Method fun2 = c1.getDeclaredMethod("fun2", String.class);
        //Violent visit
        fun2.setAccessible(true); //Only private method calls require brute force access
        fun2.invoke(o,"Digital plus Technology");
        System.out.println("=========================================");
        Method fun3 = c1.getDeclaredMethod("fun3");
        Object invoke = fun3.invoke(o);
        System.out.println("=========================================");
        Method fun4 = c1.getDeclaredMethod("fn4");
        fun4.invoke(o);


    }
}

Reflection exercises

Run the methods in the class through the configuration file

Profile:
The configuration file is basically filled with keys - values, which exist
className
com.shujia.wyh.day27.Person

public class ReflexTest1 {
    public static void main(String[] args) throws Exception {
        //Before learning reflection
//        Person person = new Person();
//        person.fun1();
//        person.fun2();

        //After learning reflection
        Properties prop = new Properties();
        FileReader fr = new FileReader("D:\\IdeaProjects\\bigdata15\\src\\com\\shujia\\wyh\\day27\\configure.txt");
        prop.load(fr);
        fr.close();

        //get data
        String className = prop.getProperty("className");
        System.out.println(className);
        String methodName = prop.getProperty("methodName");
        System.out.println(methodName);

        //Achieved by reflection
        Class<?> c1 = Class.forName(className);
        Constructor<?> cons = c1.getConstructor();
        Object o = cons.newInstance();

        //Call method through reflection
        Method fun2 = c1.getDeclaredMethod(methodName, String.class);
        //Violent visit
        fun2.setAccessible(true);
        fun2.invoke(o,"Digital plus technology, yyds");



    }
}

I'll give you an object of ArrayList. I want to add a string data to this collection. How to implement it?

public class ReflexTest2 {
    public static void main(String[] args) throws Exception {
        ArrayList<Integer> list = new ArrayList<>();
//        list.add(10);
//        list.add("hello");

        //Achieved by reflection
        Class<? extends ArrayList> listClass = list.getClass();
        Method add = listClass.getMethod("add", Object.class);
        add.invoke(list,20);
        add.invoke(list,"Hello");
        add.invoke(list,12.34);

//        for(Integer i:list){
//            System.out.println(i);
//        }

        Iterator<Integer> iterator = list.iterator();
        while (iterator.hasNext()){
            Object next = (Object)iterator.next();
            System.out.println(next);

        }



    }
}

Dynamic agent

Agent: someone else is invited to do what should be done by themselves. The person invited is the agent.
For example: buy tickets at home in spring and let others buy them
Dynamic agent: this object generated during the running of the program
The object generated in the process of program running is actually the content we just explained by reflection. Therefore, dynamic agent is actually to generate an agent through reflection

In Java, Java Lang.reflect package provides a Proxy class and an InvocationHandler interface, which can be used to generate dynamic Proxy objects. The agent provided by JDK can only act as an agent for the interface. We have a more powerful agent cglib
The method in the Proxy class creates a dynamic Proxy class object
Object invoke(Object proxy,Method method,Object[] args)public static Object newProxyInstance(ClassLoader loader,Class<?>[] interfaces,InvocationHandler h)
The InvocationHandler method will eventually be called
InvocationHandler

General review and subsequent planning

1:  First acquaintance Java
1,What is a computer
2,DOS
3,Java
4,JDK,JRE,JVM
5,install JDK
6,Configure environment variables
7,HelloWorld
8,java Running steps

II Java Basic grammar
1,notes
2,keyword
3,identifier 
4,constant
5,operator
    +
    =
    ==
    ||
    &&
    ternary operator 
6,Keyboard Entry 
7,Grammatical structure
8,variable
9,Methods and arrays

3, Object oriented
 encapsulation
 inherit
 polymorphic

4, Common class
Object
String
StringBuffer,StringBuilder
Arrays
 Custom tool class document comments

5, Assemble
Collection
Map

Vi IO
 abnormal
File
 recursion
 Byte stream
 Character stream
 Serialized stream

7, Multithreading
 Three ways to implement threading
 Solution to thread synchronization security:
    1,synchronized keyword
    2,lock lock
 deadlock
 Wait for wake-up mechanism
 Thread pool (just know the difference between several thread pools)

8, Network programming
UDP
TCP

9, Reflection (just read and knock the cases in class)


Future learning route:
Linux

MySql on Linux

Springboot combination mysql Data addition, deletion, modification and query are displayed on the page
redis

hadoop

hive(Practice at least 2 times a day hive topic)

hbase

...

Topics: Java Big Data udp TCP/IP