1. Singleton mode
package day_25text; /** * Single example: a class is obtained multiple times and only one object is obtained * * 1 Construction method privatization * * 2 Static variable storage object * * 3 Public static method for getting objects * * @author Learn bald Zhang *@Date 2021 October 31, 2013 3:55:36 PM */ public class Text02 { private Text02() { } // volatile: prevent instruction rearrangement private volatile static Text02 s = null; // public synchronized static Singleton_01 getInstance() { public static Text02 getInstance() { if (s == null) { synchronized (Text02.class) { if (s == null) { s = new Text02(); } } } return s; } }
2. Producers and consumers
package day_25text; public class Text03 { public static void main(String[] args) { SynStack s = new SynStack(); Thread t1 = new Thread(new Producer(s)); Thread t2 = new Consumer(s); t1.start(); t2.start(); } } class Producer implements Runnable{ SynStack s; public Producer(SynStack s) { super(); this.s = s; } @Override public void run() { for (int i = 0; i < 20; i++) { s.push((char)(i+'a')); } } } class Consumer extends Thread{ SynStack s; public Consumer(SynStack s) { super(); this.s = s; } @Override public void run() { for (int i = 0; i < 20; i++) { char c = s.pop(); } } } // Business class class SynStack { char[] data = new char[6]; // The number of added elements is also the subscript of the next element int count = 0; // Producer: wait when the inventory is full // Consumer: wait when there is no inventory public synchronized void push(char c){ // Determine whether the inventory is full if (count >= data.length) { // If full, enter the waiting try { // Consumers are waiting when the inventory is gone // And here are full, indicating that consumers have not entered the waiting state this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } // That means it's not full // When the inventory is 1, it is not full, and when the inventory is 0, the consumer enters the waiting mode // Therefore, here consumers may enter the waiting, and consumers should be awakened if (count == 0) { this.notifyAll(); } // Add inventory data[count] = c; count++; System.out.println("Produced : "+c + " also : "+count+" Inventory"); } public synchronized char pop(){ // Determine whether there is inventory if (count == 0) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } // If there is inventory here, you can be reminded to produce as long as the inventory is not full if (count < 6) { this.notifyAll(); } count--; char c = data[count]; System.out.println("Consumption : "+c + " also : "+count+" Inventory"); return c; } }
3. Network programming
3.1 general
Java is the language on the Internet. It provides the expenditure on network applications at the language level. Programmers can easily develop common network applications
The network class library provided by java can realize painless network connection. The underlying details of networking are hidden in the Java Native installation system and controlled by the JVM. Moreover, Java implements a cross platform network library, and programmers face a unified network programming environment
3.2 network foundation
Computer network:
Computers distributed in different geographical regions and special external equipment are interconnected by communication lines to form a large-scale and powerful network system, so that many computers can easily transfer information and share hardware, software, data information and other resources.
Purpose of network programming:
Data exchange and communication with other computers directly or indirectly through network protocol.
There are two main problems in network programming:
How to accurately locate one or more hosts on the network; Locate a specific application on the host
How to transfer data reliably and efficiently after finding the host
3.3 network communication
Address of both parties
a)IP
b) Port number
Certain rules (i.e. network communication protocol. There are two sets of reference models)
c)OSI reference model: the model is too idealized to be widely popularized on the Internet
d)TCP/IP reference model (or TCP/IP Protocol): a de facto international standard
3.3.1 communication element 1:IP address
·IP address: InetAddress
Uniquely identifies the computer (communication entity) on the Internet
Local loopback address: 127.0.0.1 hostname: localhost
IP address classification method 1:IPV4 and IPV6
IPV4: it consists of four bytes, four 0-255, about 4.2 billion and 3 billion, all in North America and 400 million in Asia. It has been exhausted in early 2011. It is expressed in dotted decimal system, such as 192.168.0.1
IPV6:128 bits (16 bytes), written as 8 unsigned integers. Each integer is represented by four hexadecimals, and the numbers are separated by colons (:), such as 3ffe:3201:1401:1280:c8ff:fe4d:db39:1984
IP address classification method 2: public network address (used by the World Wide Web) and private address (used by the LAN). 192.168. The private address starts with 192.168.0.0 -- 192.168.255.255, which is specially used within the organization
Features: not easy to remember
3.3.2 communication element: port number
·The port number identifies the process (program) running on the computer
Different processes have different port numbers
Defined as a 16 bit integer 0~65535.
Port classification;
Recognized ports: 0 ~ 1023. Occupied by predefined service communication (e.g. HTTP occupies port 80, FTP occupies port 21, Telnet occupies port 23)
Registration port: 1024 ~ 49151. Assigned to user processes or applications (for example, Tomcat occupies port 8080, MySQL occupies port 3306, Oracle occupies port 1521, etc.)
Dynamic / private ports: 49152 ~ 65535
·The combination of port number and IP address yields a network Socket: Socket
3.4 network protocol
3.4.1 TCP protocol
3.4.1.1 overview
·There are two very important protocols in the transport layer protocol:
Transmission control protocol (TCP)
User datagram protocol (UDP)
·TCP/IP is named after its two main protocols: transmission control protocol (TCP) and network interconnection protocol (IP). It is actually a group of protocols, including multiple protocols with different functions and related to each other
·IP(Internet Protocol) protocol is the main protocol of network layer, which supports data communication between networks
·From a more practical point of view, TCP/IP protocol model forms an efficient four layer architecture, namely physical link layer, IP layer, transport layer and application layer
TCP
/** * TCP : Order: the order will not be disordered * Reliable, connection oriented. Data can only be sent after successful connection * Able to retransmit: no data is lost. If it is lost, it will be recorded and sent again * Need to go back and forth, referred to as three handshakes * * @author Learn bald Zhang *@Date 2021 October 31, 2013 10:30:10 PM */
3.4.1.2Socket
Using socket to develop network applications has long been widely used, so that it has become a de facto standard.
The IP address and port number with unique identification on the network can be combined to form a unique identifier socket.
Socket s are required at both ends of the communication, which are the communication endpoints between two machines.
Network communication is actually the communication between sockets.
Socket allows the program to treat the network connection as a stream, and the data is transmitted between the two sockets through IO.
Generally, the application that initiates communication actively belongs to the client, and the one waiting for communication request is the server.
Socket classification:
stream socket: use TCP to provide reliable byte stream service. datagram socket: use UDP to provide "best effort" datagram service
3.4.1.3 common methods
·Common constructors of Socket class:
public Socket(InetAddress address,int port) creates a stream socket and connects it to the specified port number of the specified IP address.
public Socket(String host,int port) creates a stream Socket and connects it to the specified port number on the specified host. · common methods of Socket class:
public InputStream getInputStream() returns the input stream of this socket. Can be used to receive network messages
public OutputStream getOutputStream() returns the output stream of this socket. It can be used to send network messages
public InetAddress getInetAddress() the remote to which this socket is connected IP address; Returns if the socket is not connected null
public InetAddress getLocalAddress() gets the local address of the socket binding. That is, the IP address of the local end
public int getPort() the remote port number to which this socket is connected; Returns if the socket is not connected 0
public int getLocalPort() returns the local port to which this socket is bound. Returns if the socket has not been bound - 1. That is, the port number of this end
public void close() closes the socket. After the socket is closed, it cannot be used in future network connections (that is, it cannot be reconnected or rebound). A new socket object needs to be created. Closing this socket will also close the of the socket InputStream and OutputStream
public void shutdownInput() if called on a socket After shutdownInput(), the content is read from the socket input stream, and the stream will return EOF (end of file). That is, no data can be received in the input stream from this socket
public void shutdownOutput() disables the output stream for this socket. about TCP socket, any previously written data will be sent, followed by Normal connection termination sequence of TCP. If called on a socket Write socket output stream after shutdown output(), The stream will throw IOException. That is, no data can be sent through the output stream of this socket
3.4.1.4 server
·The working process of the server program includes the following four basic steps:
call ServerSocket(int port): create a server-side socket and bind it to the specified port. Used to listen for client requests
call accept(): listen for connection requests. If the client requests a connection, it accepts the connection and returns the communication socket object
call The name of the Socket class object getOutputStream() and getInputStream(): get the output stream and input stream and start sending and receiving network data
Close ServerSocket and Socket object: end client access and close communication Socket
·The ServerSocket object is responsible for waiting for the client to request to establish a socket connection, similar to the salesman in a window of the post office. In other words, the server must establish a ServerSocket object waiting for the client's request to establish a socket connection in advance
·The so-called "receiving" the client's socket request is that the accept() method will return a Socket object
package day_25text02; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; public class Text02 { public static void main(String[] args) throws Exception { // 1 create object open port ServerSocket ss = new ServerSocket(10001); System.out.println("Server started,Waiting for connection..."); // The execution here will enter the wait, waiting for the client to connect // Return client object Socket skt = ss.accept(); System.out.println("Client connected"); // Response information to the client // Get output stream OutputStream os = skt.getOutputStream(); PrintWriter pw = new PrintWriter(new OutputStreamWriter(os, "gbk")); // Get input stream InputStream is = skt.getInputStream(); // Convert to character input InputStreamReader isr = new InputStreamReader(is, "gbk"); // Convert to character input buffer stream BufferedReader br = new BufferedReader(isr); String temp = null; while ((temp = br.readLine()) != null) { // Get client data System.out.println("Message from client : "+temp); // Send data to client pw.println("Your feedback '"+temp+"' We have received,Reply to you as soon as possible."); pw.flush(); } }
3.4.1.5 client
·The working process of the client Socket includes the following four basic steps:
establish Socket: according to the of the specified server IP address or port number structure Socket class object. If the server responds, a communication line from the client to the server is established. If the connection fails, an exception will appear
Open the input / output stream connected to the Socket: use getInputStream() method obtains the input stream, and getOutputStream() method obtains the output stream for data transmission
Read / write the Socket according to a certain protocol: read the information put into the line by the server through the input stream (but you can't read the information put into the line by yourself), and write the information into the thread through the output stream
close Socket: disconnect the client from the server and release the line
·The client program can use the Socket class to create objects, which will automatically initiate a connection to the server at the same time. The constructor of the Socket is:
Socket(String host,int port)throws UnknownHostException,IOException: initiates a TCP connection to the server (the domain name is host and the port number is port). If successful, the socket object is created, otherwise an exception is thrown
Socket(InetAddress address,int port)throws IOException: initiates a connection according to the IP address and port number represented by the InetAddress object.
·The process that the client establishes the socketAtClient object is to send a socket connection request to the server
package day_25text02; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.Socket; import java.util.Scanner; public class Text01 { public static void main(String[] args) throws Exception { // Create object, bind IP and port Socket skt = new Socket("127.0.0.1", 10001); // Get the information transmitted by the server // Get input stream InputStream is =skt.getInputStream(); // Convert to character input InputStreamReader isr = new InputStreamReader(is,"gbk"); // Convert to character input buffer stream BufferedReader br = new BufferedReader(isr); // Response information to the server // Get output stream OutputStream os = skt.getOutputStream(); PrintWriter pw = new PrintWriter(new OutputStreamWriter(os, "gbk")); String temp = null; Scanner scanner = new Scanner(System.in); while (!(temp = scanner.nextLine()).equals("sign out")) { pw.println(temp); pw.flush(); System.out.println(br.readLine()); } br.close(); isr.close(); is.close(); skt.close(); } }
3.4.2 UDP protocol
3.4.2.1 overview
/** * UDP : High speed, unreliable, possible packet loss and no connection * * @author Learn bald Zhang *@Date 2021 October 31, 2013 10:30:10 PM */
·Class Datagram socket and Datagram packet implements UDP protocol network program
·UDP datagram through datagram socket When sending and receiving datagram socket, the system does not guarantee that UDP datagrams can be safely sent to the destination, nor can it determine when they can arrive. The datagram packet object encapsulates UDP datagrams, which contain the IP address of the sender Address and port number and the IP address and port number of the receiving end
·Each datagram in UDP protocol gives complete address information, so there is no need to establish a connection between the sender and the receiver. It's like sending an express package
3.4.2.2 common methods
Common methods of DatagramSocket class
Public datagram socket (int port) creates a datagram socket and binds it to the specified port on the local host. The socket is bound to a wildcard address, and the IP address is selected by the kernel
Public datagram socket (int port, InetAddress, ladder) creates a datagram socket and binds it to the specified local address. The local port must be 0 to 65535 (both included). If The IP address is 0.0.0.0, the socket will be bound to the wildcard address, and the IP address is selected by the kernel
public void close() closes the datagram socket. Public void send (datagram packet P) sends datagram packets from this socket. The datagram packet contains information indicating the data to be sent, its length, and the location of the remote host IP address and port number of the remote host
Public void receive (datagram packet P) receives datagram packets from this socket. When this method returns, DatagramPacket The buffer of is filled with the received data. The datagram packet also contains the information of the sender IP address and port number on the sender's machine. This method blocks until a datagram is received. Of datagram packet objects The length field contains the length of the received information. If the message is longer than the length of the packet, the message will be truncated
public InetAddress getLocalAddress() gets the local address of the socket binding. public int getLocalPort() returns the port number on the local host to which this socket is bound
public InetAddress getInetAddress() returns the address of this socket connection. Returns null if the socket is not connected
public int getPort() returns the port of this socket. Returns if the socket is not connected - one
Common methods of DatagramPacket class
Public datagram packet (byte [] buf, int length) structure Datagram packet, which is used to receive data packets with length. The length parameter must be less than or equal to buf.length
Public datagram packet (byte [] buf, int length, InetAddress, address, int port) constructs a datagram packet with a length of The packet of length is sent to the specified port number on the specified host. length Parameter must be less than or equal to buf.length
public InetAddress getAddress() returns the name of a machine IP address, this datagram will be sent to or received from the machine
public int getPort() returns the port number of a remote host to which this datagram will be sent or received
public byte[] getData() returns the data buffer. The offset of data received or to be sent from the buffer Start at offset and last for length
public int getLength() returns the length of the data to be sent or received
3.4.2.3 client
package day_25text02; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress; import java.util.Scanner; public class Text03 { public static void main(String[] args) throws Exception{ Scanner scanner = new Scanner(System.in); String string = scanner.nextLine(); // 1 byte array stream -- > data stream writes out to byte array stream -- > byte array // 2-byte array -- > Convert to byte array stream -- > data stream read data in byte array stream while (string != null && !string.equalsIgnoreCase("exit")) { // Convert data to byte array stream ByteArrayOutputStream bos = new ByteArrayOutputStream(); // Convert to data stream for data transfer DataOutputStream dos = new DataOutputStream(bos); // Write string into data stream dos.writeUTF(string); // Convert to byte array byte[] bytes = bos.toByteArray(); // The server address and port are where the packet is sent InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 10001); // Data transfer, packaging DatagramPacket dp = new DatagramPacket(bytes, bytes.length,inetSocketAddress); // The client port needs to be opened for transmission DatagramSocket ds = new DatagramSocket(9999); // Datagram packet: data packet // Datagram socket: data communication // send out ds.send(dp); ds.close(); System.out.println("Please enter the information passed"); string = scanner.nextLine(); } } }
3.4.2.4 server
package day_25text02; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.net.DatagramPacket; import java.net.DatagramSocket; public class Text04 { public static void main(String[] args) throws Exception{ // 1 open the UDP object and listen on the port DatagramSocket ds = new DatagramSocket(10001); // Byte array to hold data byte[] bytes = new byte[1024]; // Packet receiver DatagramPacket dp = new DatagramPacket(bytes,bytes.length); while (true) { // Receive data through an open port ds.receive(dp); // Convert to byte array stream ByteArrayInputStream bais = new ByteArrayInputStream(bytes); // Read data using data stream DataInputStream bis = new DataInputStream(bais); // Read data String data = bis.readUTF(); System.out.println(data); } } }
3.4.3 differences
TCP protocol:
Before using TCP protocol, a TCP connection must be established to form a data transmission channel
Before transmission, the "triple handshake" mode is adopted for point-to-point communication, which is reliable
Two application processes communicating with TCP protocol: client and server
A large amount of data can be transmitted in the connection
After transmission, the established connection needs to be released, which is inefficient
UDP protocol:
Encapsulate the data, source and destination into packets without establishing a connection
The size of each packet is limited to 64K
Whether the sending party is ready or not, the receiving party does not confirm the receipt, so it is unreliable
Can broadcast and send
At the end of sending data, there is no need to release resources, low overhead and high speed