Annotation and multithreading in java learning, network programming and XML technology, collection framework, etc

Run if you can't beat it 2020-11-09 14:29:12
annotation multithreading java learning network


This part mainly includes collection framework and generics , Practical Class , Input and output processing , Annotation and multithreading , Network programming and XML technology . It's hard to learn this part for the first time , The main problem is that the concept is difficult to understand , It's better to look at more examples , Practice more . Here's a personal summary

 

One 、 Collection framework and generics

1、 Collections framework

It's a set of excellent performance 、 Easy to use interfaces and classes ( be located java.util In bag ) To solve the problem that the array can not adapt to the dynamic change of the number of elements in storage , Find inefficient defects

Collection interface : Map、Collection( A subinterface List、Set) 、 Iterator

Interface implementation class :HashMap  TreeMap 、ArrayList  LinkedList、 HashSet  TreeSet   Realization map、list、set Interface

Collection tool class :Arrays 、Collections  Provides algorithms that operate on collection elements

2、 Interface differences

Collection Interface stores a set of repeatable , Disordered objects ( Include List  Set Interface )

Common methods :clear() Remove the elements    isEmpty() Determines if the set is empty

iterator() Get the iterator of the collection  toArray() Set to array

List Interface stores a set of repeatable , Orderly objects

Set The interface stores a unique set of , Disordered objects

Map Interface stores a set of key value objects , The key is the only ,Map and Set It's like

3、 Digression :

     If you encounter any problems in the learning process , Take a look at my bulletin board , Xiao Bian answers online , Help you take off , And some of the things I've been working on these days Java Learning manual , Interview questions , development tool ,PDF Document book tutorial , If you need it, you can share it for free !

4、 Interface implementation class

  • ArrayList: Allocate contiguous space in memory . According to the subscript traversal element and random access element efficiency is higher , The addition and deletion operations are slow due to the location movement

Common methods : add(Objiect o) Add elements sequentially at the end of the list

            get(int index) Returns the element at the specified index position

            size() Returns the number of elements in the list

            contains(Objiect o) Determine if a specified element exists in the list

            remove(Objiect o) Delete the elements in the list

  • LinkedList: Using linked list storage mode . All sequential searches are slow , And insert 、 You don't have to move the location when you delete an element , High efficiency

Common methods :addFirst(Objiect 0) Add elements to the top of the list

           addLast(Objiect 0) Add elements to the end of the list

           getFirst() Gets the first element of the current collection

           getLast() Get the last element of the current collection

           removeFirst() Delete and return the first element in the list

           removeFirst() Delete and return the last element in the list

  • TreeSet|TreeMap Compare : The bottom layer is a binary tree structure ;

TreeMap、TreeSet All save the order of objects ;

TreeSet Store only one object , and TreeMap Store two objects Key and Value;

Storage speed ratio Hash Slow assembly .

  • HashSet|HashMap Compare : The underlying data structure is hash table ;

HashMap Store key value pairs , Key unique , and HashSet Just store objects , The object is unique ;

HashMap Use a unique key to get the object , It's relatively fast .

  • HashSet Ensemble method :

add(Objiect o)   Add object

size()     Number of return elements

contains(Objiect o)  Judge whether it exists

remove(Objiect o) Remove related objects

  • HashMap Ensemble method :

        put(key,value) Add key value pair

        get(key)         To obtain and key About the value

        remove(key) Remove and key About the mapping , And return the old value

        containsKey( ) containsValue( ) Judge whether it exists key value

                size() Number of return elements

 keySet() Get all key Set

 values() Get all values Set

5、 A collection of traverse

Three methods : Ordinary for loop   enhance for loop  Iterator Iterator traversal

1.for (Object object : list) { System.out.println(object); }

2.for (int i = 0 ;i<list.size();i++) { int j= (Integer) list.get(i);  System.out.println(j); }

3.Iterator iterator = list.iterator();while(iterator.hasNext()){

int i = (Integer) iterator.next();  System.out.println(i); }

Iterator Method :

HasNext() Determine if there is the next accessible element , If possible , return true

Next() Returns the next element to be accessed

6、Collections Tool class

effect : Realize the sorting of elements 、 Find and replace operations

If you want to compare the size of objects in a class , Must be realized Comparable Interface .

Comparable Interface : Naturally sort the objects of each class that implements it .

comparableTo(Object obj) Method : Used to compare the order of this object with the specified object

Return value :0 be equal to 、1 Greater than 、-1 Less than the specified object obj

Method :

fill( ) A method of replacing all elements in a collection with the same element

sort( ) How to sort a set

binarySearch( ) The way to find a set

max( )\min( ) Find the maximum 、 minimum value

7、 Generic set

  • Generics are parameterized types , Constraints are implemented by specifying the element type in the collection

effect : Take the type of the object as an argument , Assign to other classes or methods , So as to ensure the security and stability of type conversion

give an example :List<Integer> list=new ArrayList<Integer>( );

ArrayList<Student> students = new ArrayList<Student>();

  •   A typical generic collection :ArrayList<E>、HashMap<K,V>

Generic classes : public class User<T>{}

Generic interface :public interface Pair<T>{}

Generic methods : public <T> void getMiddle(T[] b) {}   Be careful <T> The location of

In the generic , The basic type is that you can't do generic parameters , Only wrapper class can be used 、 Reference data type .

 

Two 、 Practical Class

1、 Basic concepts

Java API:Java The programming interface of the application program 、Java Help document

Practical Class :   from Java API Common classes provided

Learn this part must see more Java API .Java The common packages provided by the help document are as follows :

lang package : Contains base classes and interfaces   Such as Comparable Interface 、 Packaging 、  String、Math class

Util package : Contains system auxiliary classes Such as Collection、Map Interface 、 Date、Arrays class

Io package :   Classes related to input and output Such as Serializable Interface 、File、Reader、Writer class

Net package : Network related classes   Such as CookieStore Interface 、Socket、URL、ServerSocket class

Sql package : Database related classes   Such as  Statement Interface 、DriverManager、DriverPropertyInfo class

2、 enumeration

A type consisting of a fixed set of constants . Use enum Keyword definition

give an example : Definition :public enum Genders{ male , Woman } call :Genders. male

effect : Type safety 、 Easy to type 、 The code is fresh

3、 Packaging

Concept : Wrap the basic data type as an object , Facilitate the operation of objects , Embodies the java The characteristics of object-oriented . ag:int→Integer char→Character  byte→Byte

Packaging functions :

  • Facilitate the transformation between various types   Such as :int The type and String Types switch to each other

  • Provides the basic data type related properties and methods Such as : minimum value 、toString() 、valueOf()、equals() Method

Common methods :

toString(): Convert basic data type to string type

valueOf(): Static overload method The basic data type 、 String conversion to wrapper class

parseInt()、parseBoolean(): Convert the string to the corresponding basic data type

4、 Type conversion

  • Basic type to packaging class :Integer i=5; or Integer i=new Integer(5); or Integer i=new Integer(“5”); or Integer i=Integer.valueOf(“5”);

Be careful : except Character Outside the packaging category , You can use strings as parameters to construct instances

  • Packaging class to basic type :int intId=id.intvalue(); or int intId=id;

  • Automatic conversion : Integer i=5;// Packing basic → packing     int j=i;// Unpacking packing → basic

jdk 1.5 in the future , Conversion of basic types and wrapper classes , The compiler will do it automatically

5、String class

  • stay Java in , Strings are often used as String Type object to handle .

  • establish String Object methods :

String a=”hello” or String a = new String(“hello”);

Be careful : The first 2 A way , Two objects are created : One ”hello” String object , In heap memory ; One s object , In stack memory .

  • Common methods :

Judge :    equals(): Determine whether the contents of two strings are the same

equalsIgnoreCase(): Determine whether the contents of two strings are the same , Case insensitive

contains(String s): Determine whether a string contains another string

endsWith(String s): Tests whether the string ends with the specified suffix

startsWith(String s): Tests whether the string starts with the specified prefix

isEmpty(): Test whether the string is empty

obtain :    int length(): Returns the length of this string

char charAt(int index): Returns the char value ( character )

int indexOf(): Returns the specified character ( strand ) The index at the first occurrence in this string

int lastIndexOf(int c): Returns the index of the last occurrence of the specified character in this string

String substring(int beginIndex, int endIndex) Returns a new string , It's a substring of this string , Include the head, not the tail .

transformation :    byte[] getBytes(): Methods from strings to byte arrays

char[] toCharArray(): Methods from strings to character arrays

String valueOf( data type ): Convert the data of this data type to a string

String toLowerCase(): Convert a string to lowercase

String toUpperCase(): Convert a string to uppercase

String concat(String str): Connect the specified string to the end of the string

Replace segmentation : String replace(char oldChar, char newChar): Replace old characters with new ones

String[] split(String regex): Divide a string into an array of strings according to the specified string

    String trim(): Remove the space before and after the string

    int compareTo(String anotherString) Compare two strings in dictionary order

    int compareToIgnoreCase(String str) Compare two strings in dictionary order , Regardless of case

6、StringBuffer

  • This is equivalent to giving the string a buffer , yes String The enhancement class of . Frequently modify the string ( Such as string concatenation ) when , Use StringBuffer Class can greatly improve the efficiency of program execution .

  • StringBuffer Statement

StringBuffer strb = new StringBuffer();

StringBuffer strb = new StringBuffer(“aaa”);

  • Common methods :

increase :append(“**”): Appending various types of data to the string

insert (1, “**”): Insert various types of data in the specified position of the container

Delete :deleteCharAt() : Delete the characters in the specified position

    delete(): Empty StringBuffer The buffer

Replace :replace(): Replace old characters with new ones

    toString(): take StringBuffer String of type to String Object of type

obtain :charAt() : Returns the char value ( character string )

    length(): Returns the length of this string

  • JDK5.0 After that provided StringBuilder, Equivalent StringBuffer. But it's single threaded , Relatively efficient , But it doesn't guarantee thread safety .

7、Math class

Provides the common mathematical operation method and two static constants E( The base of natural logarithm ) and PI( PI )

Common methods :

abs(): Return the absolute value ;

max(): Return maximum ;

random(): Return random number

ag: Generate [0,10) The integer of the interval int random = (int)(Math.random()*10);

8、Random class

Is a class that produces random numbers

Common methods :

  • Construction method

Random() Create a new random number generator .

Random(long seed) Use a single seed to create a new random number generator .

Be careful : The seed number is just the origin number of random algorithm , It's not about the interval of the generated random number

ag:Random rand = new Random(10);

  • Member method

int nextInt() Returns the next pseudo-random number , It is evenly distributed in the sequence of the random number generator int value .

int nextInt(int n) Returns a pseudo-random number , The value is between [0,n) The range of .

ag: Generate [0,10) The integer of the interval     int num = rand.nextInt(10);

11、Scanner class

be located java.util package , Is a class that gets input data from the keyboard

  • Construction method

Scanner(InputStream source) Create a text scanner to parse basic types and strings

ag:Scanner sc = new Scanner(System.in);

  • Member method

hasNext() Determine whether there is a next segment after the current scanning position in the scanner .

hasNextLine() If there is another line in the input to this scanner , Then return to true.

nextInt()  Scan the next tag of the input information as a int, Take an integer variable .

next() Receive the next one with a newline or space as a line break String Type variable . Such as : Input hello world!, It's just hello

nextLine()  In exchange for the behavior boundary to receive the next String Type variable . Such as : Input hello world!, What was received was hello word!

12、Date class

be located java.util package , Class representing date and time

  • Construction method

Date() Distribute Date Object and initialize this object , To indicate when it was allocated ( Accurate to milliseconds ).

Date(long date) Distribute Date Object and initialize this object , From the standard base time ( namely 1970 year 1 month 1 Japan 00:00:00GMT) Specified number of milliseconds since .

  • Member method

int compareTo(Date anotherDate) Compare the order of the two dates

boolean equals(Object obj) Compare the equality of two dates .

13、SimpleDateFormat class

be located java.text package , Specific classes for formatting and parsing dates

Fixed writing :

// Create date object Date date = new Date();

// Custom date format SimpleDateFormat f= new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);

String now = f.format(date);  System.out.println(now);

14、Calendar class

be located java.util package , Used to set and get dates / Specific parts of time data

int get(int field)       Returns the value of the given calendar field

YEAR   Indication year     MONTH   Indicates the month

DAY_OF_MONTH   Indicates a day of the month

DAY_OF_WEEK         Indicate a day of the week

 

3、 ... and 、 Input / Output and reflection

 

1、File class

be located java.io package , Used to manipulate file directories and properties

  • Construction method :

File(String pathname) specify the path to a file

File(String dir,String subpath)dir Parameter specifies the directory path ,subpath Parameter specifies the file name

File(File parent,String subpath)parent Parameter specifies the directory file ,subpath Parameter specifies the file name

  • Common methods :

establish :

boolean createNewFile( )   Create an empty file with the name , Don't create a folder

boolean mkdir() Created by File Object represents the directory ( First level folder )

boolean mkdirs() Create a directory that includes the parent directory ( Secondary folder )

Judge :

boolean exists( )   Determine if a file or directory exists

boolean isFile( )    Determine if it's a document

boolean isDirectory( )   Determine if it's a directory

obtain :

String getPath( )    Returns the relative pathname of the file represented by this object

String getAbsolutePath( )    Returns the absolute pathname of the file represented by this object

String getName( )    Returns the name of the file or directory represented by this object

String getParent()   Returns the pathname of the parent directory of this object ;

long length()   Returns the length of the file , The unit is byte , If the file doesn't exist , Then return to 0L

Delete :

boolean delete( )    Delete the file or directory specified by this object

2、 Relative path and absolute path

Relative paths : Starting from the middle catalog , Path to the current location .

Absolute path : Starting from the root directory , The path to the current location .

3、Java IO flow

Refers to a binary sequence of bytes , It's a stream of flowing characters , It's a first in, first out channel to send messages

classification :

(1) Data types are divided into..., according to the type of data that flows : Byte stream and character stream .

Byte stream is 8 Bit Universal byte stream , The character stream is 16 position Unicode Character stream

(2) According to the flow direction, it is divided into : Input stream , Output stream ( Compared with computer programs , First in, then out 、 First learns to write )

Source data source ( keyboard 、 Hard disk )→ Input stream ( read )→ Program → Output stream ( Write )→ Target data source ( Console )

4、IO Streams are often used as base classes

Be careful :( ) There are subclasses in it Such as File** class ,Buffered** class

Buffered** Class with buffer , There are lines of reading readLine() Method

  • Byte stream

Byte input stream :InputStream    (FileInputStream、BufferedInputStream)

Byte output stream :OutputStream (FileOutputStream、BufferedOutStream)

  • Character stream

Character input stream :Reader (FileReader、BufferedReader)

Character output stream :Writer  (FileWriter、BufferedWriter)

5、 Common base class methods

  • Byte input stream InputStream Class method

void close() Close this input stream and release all system resources associated with the stream

int read() Read a byte of data

int read(byte[] b) Read a certain number of bytes , And store it in the array

int read(byte[] b, int off, int len)  Maximum number of input streams len Data bytes , Save to byte array b in

  • Byte output stream OutputStream Class method

void close() Close the output stream and release all system resources related to the stream

write(int b)  Write a byte of data

void write(byte[] b) Write array b All bytes of

void write(byte[] b, int off, int len) Set the byte array from the offset off At the beginning len Bytes written to the output stream

  • Character input stream Reader Class method

void close() Close input stream

int read() Read a single character

int read(char[] c)   take c.length The length of the character is read into the array c in

int read(char[] c, int off, int len) Will be at most len The length of the character is read into the array c, Save from off Position start

  • Character output stream Writer Class method

void close() Close output stream

void flush() Refresh output stream

int read() Read a single character .

int read(char[] cbuf)   Read characters into an array

int read(char[] cbuf, int off, int len) Reading characters into a part of an array

6、 Node flow and wrapper flow

Node flow : When you create an object , The parameter is a string or File Class object

Packaging flow : When you create an object , Parameters are stream objects .

The role of packaging :1. Increase of efficiency 2. Easy to write code

7、 Use byte stream to read and write text files

  • Use FileInputStream Read the text file

// Construct a byte input stream object

FileInputStream fis= new FileInputStream(“c:\\test.txt”);

// Loop read file data   Finally, close the stream object fis.close();

System.out.println(“ The number of bytes that can be read ”+fis.available());

byte []buf = new byte[1024];   int len=0;

while((len=fis.read(buf))>0){ System.out.write(buf, 0, len); }

  • Use FileOutputStream Write a text file

// Construct a byte input stream object

FileOutputStream fos=new FileOutputStream(“f:/java.txt”);

// Write data to a text file Finally, close the stream object fos.close();

int num=12345;String s=String.valueOf(num);

fos.write(s.getBytes(), 0, s.getBytes().length);

8、 Use character stream to read and write text files

  • Use FileReader/BufferedReader Read the file

// establish FileReader/BufferedReader object

Reader fr= new FileReader(“D:\\myDoc\\ brief introduction .txt”);// Node flow

BufferedReader br=new BufferedReader(fr); // Packaging flow

// call readLine() Method to read data from a text file   Finally, close the stream object

String s=null; while((s=br.readLine())!=null){…}

  • Use FileWriter/BufferedWriter Writing documents

// establish FileWriter/BufferedWriter object

FileWriter fw= new FileWriter(“D:\\myDoc\\ brief introduction .txt”);

BufferedWriter bw=new BufferedWriter(fw);

// call write() Method to write data in a text file   Finally, close the stream object

fw.write();  fw.close();

9、 Solve the Chinese garbled code when reading

// Use InputStreamReader And set the encoding format

InputStreamReader fr=new InputStreamReader(fis,”UTF-8”);

// Read as an array of bytes

byte []buf = new byte[1024];  fis.read(buf)

10、 Read write binary

  • Use FileInputStream/DataInputStream Read binary

// Construct data input objects

FileInputStream fis=new FileInputStream(“C:\\HelloWorld.class”);

DataInputStream dis=new DataInputStream(fis);

// call read() Method reading

dis.readInt();  dis.close();

  • Use FileOutputStream/DataOutputStream Write binary

// Construct data output object

FileOutputStream outFile=newFileOutputStream(“C:\\temp.txt”);

DataOutputStream out=new DataOutputStream(outFile);

// call write() Method write

out.write();  out.close();

11、 Serialization and deserialization

serialize : The process of writing the state of an object to a specific stream . object —> flow

Deserialization : The process of retrieving data from a particular stream and rebuilding an object . flow —> object

effect :Java After object serialization , The resulting binary byte sequence can be easily saved to disk or cloud . Binary sequences can be easily transmitted across platforms , Don't worry about displaying exceptions due to platform problems .

Implementation steps :

1、 Realization Serializable Interface

2、 Create an object output stream ObjectOutputStream( serialize )/ Input stream ObjectInputStrean( Deserialization )

3、 call writeObject()/readObject () Method to write an object to a file ( serialize )/ Read the object ( Deserialization )

4、 Close object input stream

Be careful : Use transient When a keyword modifies some properties of an object , These properties will no longer be serialized

12、java Reflection

Reflection : finger java Programs can self describe and control themselves , It allows programs to load at runtime 、 Ascertain 、 Use classes that are completely unknown during compilation

The reflex mechanism : In running state , The function of dynamically obtaining class information and calling object methods dynamically

Reflex common API:

Class class — You can get class and class member information

Field class — Properties of accessible classes

Method class — Methods of callable classes

Constructor class — Constructors of callable classes

Steps to use reflection :

1、 Import java.lang.reflect.*;

2、 Get the operation class Class object

3、 call Class Method to obtain Field、Method Objects such as

4、 Using reflection API To operate

Application of reflection :

obtain Class object :getClass() Method  Class.forName() Method  .class Method

establish Class object :newInstance() Method

Access the properties of a class :getXxx() Method  setXxx() Method

        Method to access class :getMethod() Method  invoke() Method

 

Four 、 Annotations and multithreading

1、 annotation

Java Special tags in code . It's for adding... To the code Java Additional information that cannot be expressed by a program provides a formalized way . Annotations can be seen as modifiers , Modifying program elements .

Annotations can be compiled 、 Class loading 、 Read at run time . Comments are not read by the program .

2、 Annotation classification

(1) Built in notes : Standard annotation types ;

@Overrid Qualify override parent method

@Deprecated The sign is out of date

@SuppressWarnings Suppress compiler warnings

(2) Yuan notes : Modify other annotation definitions

@Target   Specifies which program elements can be decorated with annotations decorated with them

@Retention   Specifies that the annotation can be read using reflection

@Documented   The annotation will be specified JavaDoc Tools to extract documents

@Inherited   Specifies that annotations decorated with it will be inherited

(3) Custom annotation : Annotation type is an interface

Use keywords @interface Define new annotations

Such as :public @interface AnnotationTest{}

3、 Read annotation information

AnnotatedElement Interface is the parent interface of all program elements , Specifies the program elements in the program that accept annotations . Get object information through reflection .

getAnnotation() Method : Returns the... That exists on the program element 、 Specifies the type of annotation

getAnnotations() Method : Returns all comments that exist on the program element

4、 Processes and threads

  • Program : It's a collection of code that describes and operates on data .

  • process : Refers to a dynamic execution of a program . It is the basic unit of system operation program , There is independent memory space and system resources

  • Threads : An execution process in a process . Is the smallest unit of operations in the process , What really runs on a processor is threads , There must be at least one thread in a process .

  • Thread creation and start :

(1) Inherit java.lang.Thread class         Such as :class MyThread extends Thread{}

(2) Realization java.lang.Runnable Interface Such as :class MyThread implements Runnable{}

All need to be rewritten run() Method , call start() Method

MyThread myThread = new MyThread();      new Thread(myThread).start();

5、 Thread state

    Blocking | Sleep state

Freshman state —> Operational state <—> Running state —> Death state

Freshman state : Thread object has been created , It's not called on it yet start() Method .

Operational state : When a thread is eligible to run , But the scheduler has not yet chosen it as the state in which the thread is running .

Running state : The thread scheduler selects a thread from the runable pool as the current thread's state

wait for / Blocking / Sleep state : Is a thread qualified to run 、 It's just that there is no condition for the thread to wake up to its state .

Death state : Thread run() When the method is complete, the thread is considered dead

6、 Thread scheduling

Multiple threads are running , Thread scheduling determines the order in which threads enter the runnable state based on priority .

The priority of the thread is used 1~10 Express ,10 The highest priority , The default value is 5

set priority :setPriority(int grade)   Such as :myThread.setPriority(3);

Scheduling method :

join(): Add the specified thread to the current thread . First execute the thread calling the method, and then continue to execute the thread

sleep(): The current thread stops execution within the specified milliseconds and goes to a non running state

 yield(): The current thread is in a state where it is temporarily stopped

7、 Thread synchronization

When two or more threads need to access the same resource , It needs to be in some order to ensure that the resource can only be used by one thread at a time . Synchronization is equivalent to locking , The locked thread first accesses the resource , Other threads wait .

Thread synchronization :

Synchronization method : use synchronized Methods of keyword modification

public synchronized void save(){}

Synchronization code block : use synchronized Keyword decorated code block

synchronized(object){}

Be careful : Multithreading uses synchronization ” Deadlock ” The potential danger of .

Deadlock : If multiple threads are in a wait state and cannot be woken up , It's a deadlock . For example, the synchronization method has sleep() Method , Then the lock becomes a deadlock .

8、 Thread communication

Thread synchronization can prevent concurrent access to the same resource , But it can't realize the message passing between different threads . So we need to use thread communication . Note that the following methods can only be used in synchronous methods or synchronized code blocks

wait() Method :

Suspends the current thread , And release the lock of shared resources

notify() Method : Wake up the thread

When the object is called by the wait() Method and randomly select one thread to unblock , But it will not be executed until the lock is obtained

notifyAll() Method :

        Will call the object's wait() Method to unblock all threads at once

 

5、 ... and 、 Network programming technology

 

1、 Basic concepts

The Internet : It's information transmission 、 receive 、 Shared virtual platform , Put the dots 、 Noodles 、 Body information is linked together , In order to achieve resource sharing

Network programming : Programming for communication between processes by using sockets

2、IP Address (Internet Protocol)

Concept : Uniquely identify every computer on the network

IP form :32 position , from 4 individual 8 Bit binary number composition (ipv4)

11000000.10101000.00000001.11001000–>192.168.1.200

IP Address = network address + The host address

2016-08-28_152546

 

2016-08-28_152546

3、IP testing

see IP Address :cmd—ipconfig

Check if the network is unblocked :ping IP Address

4、DNS

Domain name resolver , hold IP Address mapping to domain name . Realize website visit through domain name

5、 Network server

In the network environment , With high computing power , A computer that provides user service ( Mail server ;web The server Such as Apache Tomcat Alibaba cloud )

The client → The server (Client/Server) ( c/s)

browser → The server (Browser/Server)( b/s)

6、 Network communication protocol

Rules established to communicate between different computers in a network 、 A set of standards or conventions

 Network protocol

 

 Network protocol

application layer     HTTP FTP TFTP  SMTP  SNMP  DNS agreement

Transport layer     TCP     UDP  agreement

The network layer      ICMP   IGMP  IP  ARP  RARP  agreement

Data link layer and physical layer       A protocol defined by the underlying network

7、Socket Programming

  • Socket( Socket ): It's the endpoint of the communication link . It's also Java Provided interface . because Socket The underlying mechanism is complex , therefore Java Provides API It's convenient for us to use Socket Programming

  • Socket Communication model : In network communication ,Socket Data flow is needed to complete the data transmission

  • Streaming socket : be based on TCP Agreed Socket Network programming

1、 client Socket class

// Create a client Socket

Socket socket = new Socket(“localhost”, Port parameters )

// Through output stream , Send a request getOutputStream( ) write()

      OutputStream os=Socket.get OutputStream( );

      byte[] infos=info.getBytes();

      os.write(infos);

// Close output stream

      socket.shutdownOutput();

      Through the input stream , Receiving server response

      Inputstream  is = socket.getInputStream();

// Release resources

2、 Server side ServerSocket class

// Create a server Socket

      ServerSocket serverSocket=new ServerSocket(5000)

// Use accept() Method to wait for communication from the client

     Socket socket=serverSocket.accpet();

// Get the input stream , Get client request

InputStream is=socket.getInputStream();

      Wrap the resulting byte stream into a character stream

BufferedReader br=new BufferedReader(new IputStreamReader(is));

// Through output stream , Send a response

OutputStream os = socket. getOutputStream();  Os.write(replys);

// Release resources

  • Packet socket : be based on UDP Agreed Socket Network programming

① utilize DatagramPacket Object encapsulates packets

② utilize DatagramSocket Send packet (send())

③ utilize DatagramSocket Receive packets (receive())

④ utilize DatagramPacket Processing packets

  • TCP And UDP The difference between

               TCP                       UDP

Is it connected               Connection oriented                 For unconnected

Transmission reliability           Safe and reliable                 unreliable

Speed                      slow                             fast

 


6、 ... and 、XML technology

 

1、XML brief introduction

XML(Extensibel Markup Language): Can extend markup language , It is a simple data storage language , Use a few columns of simple tags to describe the data .

characteristic : And the operating system 、 The development platform has nothing to do with ; Uniform norms

effect : Data interaction ; Configure applications and websites ;Ajax footstone

2、XML The basic structure

(1)XML Statement . Such as :<?xml version=”1.0” encoding=”UTF-8”?>

(2) The only root element . Such as : <books> </books>

(3) The elements describe information .   Such as <book id=”1”><title>java Programming idea </title></book>

3、XML label

< Element name   Property name = “ Property value ”> Element content </ Element name >

Such as :<id name=”id”  column=”id”>  <generator class=”sequence”/>  </id>

Be careful : Attribute values are wrapped in double quotation marks . Multiple attributes are separated by spaces

4、XML Escape character

< Corresponding to the transfer character &lt;           >   Corresponding to the transfer character &gt;

” Corresponding to the transfer character &quot;      ’ Corresponding to the transfer character &apos;

& Corresponding to the transfer character &amp;

When there are many special characters in the element , have access to CDATA section :<![CDATA[from Student where sid=?]]>

5、XML Parser

Non validating parsers : Check if the document format is good (eclipse Bring their own )

Validating parsers :  Use DTD( Document type definition ) or Schema Check the validity of the document

6、XML Namespace

How to write it :< xmlns:name=”url”>

give an example :xmlns:canon=”http://www.canon” –XML Namespace

xmlns=”http://www.Aptech_edu.ac”  — Attribute namespace

7、 analysis XML technology

DOM( Document object model ): hold XML The document maps to an inverted tree

  • DOM: be based on XML Parsing of document tree structure . For multiple visits XML file . characteristic : Compare the consumption of resources

step :

1. Create parser factory objects

DocumentBuilderFactory  dbf=DocumentBuilderFactory.newInstance( );

2. Parser factory objects create parser objects

DocumentBuilder  db = dbf.newDocumentBuilder( );

3. The parser object specifies XML File creation Document object

Document  document = db.parse(“ The path to be resolved ”)

4. With Document Object as the starting point operation DOM Trees

NodeList  dogList= document.getElmentsByTagName(“ node ”)

DOM Interface method

Document Interface :

getElementById()getElementsByTagName() getElementsByName() Other methods

Node Interface :

getparentNode() getchildNodes() getfirstChild() getlastChild()

getnextSibling () getpreviousSibling() createTextNode( ) removeChild() Other methods

Element Interface :

getTagName()  createElement( ) Other methods

  • SAX: Event based parsing . It's suitable for large amounts of data XML file . characteristic : Less occupied resources , Low memory consumption

  • DOM4J: Very good Java XML API. Excellent performance 、 Powerful . characteristic : Open source

DOM4J analysis XML Method

// establish SAXReader object   SAXReader reader = new SAXReader();

// obtain XML Document object    Document document = reader.read(“xml/users.xml”);

// obtain root( root ) node    Element root = document.getRootElement();

// Gets all the child node collections under the node  List<Element> users=root.elements();

// Traverse the output  for(Element user:users){…}

DOM4J establish XML Method

// Created a xml file

Document document=DocumentHelper.createDocument();

// Create a root node And a child node And add properties

Element root=document.addElement(“users”);

Element user = root.addElement(“user”).addAttribute(“id”, “1”);

// Set the text of the child node

user.addElement(“username”).addText(“zs”);

user.addElement(“password”).addText(“111”);

// Create an output stream object

File file = new File(“src/xml/users.xml”);

FileOutputStream out = new FileOutputStream(file);

// Create a XMLWriter The object of   call write Method write

       writer=new XMLWriter(out, OutputFormat.createPrettyPrint());  writer.write(document);

 

7、 ... and 、 Related codes

 

 

 

 

 

 

 

 

 

 

This article concludes here for the time being , More will be shared later Java The data Department on the way to study


This article is over here , More will be shared later Java Learn the information and details on the way , If you like, you can pay attention to !!!

 

版权声明
本文为[Run if you can't beat it]所创,转载请带上原文链接,感谢

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云