1. Singleton mode
Single example: a class is obtained multiple times and only one object is obtained
1. Privatization of construction method
2 static variable storage object
3 public static method for obtaining objects
public class Singleton_01 { private Singleton_01() { } // volatile: prevent instruction rearrangement private volatile static Singleton_01 s = null; // public synchronized static Singleton_01 getInstance() { public static Singleton_01 getInstance() { if (s == null) { synchronized (Singleton_01.class) { if (s == null) { s = new Singleton_01(); } } } return s; } }
2. Network programming
2.1 general
Java is a language on the Internet. It provides support for 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. And Java implements a cross platform network library. Programmers face a unified network programming environment.
2.2 network foundation
Computer network:
u interconnect computers distributed in different geographical regions with special external equipment with 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 with each other.
l purpose of network programming:
u realize data exchange and communication with other computers directly or indirectly through network protocol.
u there are two main problems in network programming:
u how to accurately locate one or more hosts on the network; Locate a specific application on the host
u how to transmit data reliably and efficiently after finding the host
2.3 network communication
Address of both parties:
IP
Port number
Certain rules (i.e. network communication protocol. There are two sets of reference models):
OSI reference model: the model is too idealized to be widely popularized on the Internet
TCP/IP reference model (or TCP/IP Protocol): a de facto international standard.
2.3.1 communication element 1: IP address
IP address: InetAddress
(1) Unique identification Computers on the Internet (communication entities)
(2) Local loopback address: 127.0.0.1 hostname: localhost
(3) IP address classification method 1: IPV4 and IPV6
1) IPV4: 4 bytes, 4 0-255. About 4.2 billion and 3 billion are in North America and 400 million in Asia. It was exhausted in early 2011. Expressed in dotted decimal system, such as 192.168.0.1
2) IPV6: 128 bits (16 bytes), written as 8 unsigned integers. Each integer is represented by four hexadecimal bits, separated by colons (:), such as 3ffe:3201:1401:1280:c8ff:fe4d:db39:1984
(4) IP address classification method 2: public network address (used by the World Wide Web) and private address (used by the local area network). 192.168. At the beginning is the private address, which ranges from 192.168.0.0 to 192.168.255.255. It is specially used within the organization
(5) Features: not easy to remember
2.3.2 communication element 2: port number
The port number identifies the process (program) running on the computer:
(1) Different processes have different port numbers
(2) Defined as a 16 bit integer 0~65535.
(3) Port classification:
1) Recognized port: 0 ~ 1023. Occupied by predefined service communication (e.g. HTTP occupies port 80, FTP occupies port 21, Telnet occupies port 23)
2) Registration port: 1024 ~ 49151. Assigned to a user process or application. (for example, Tomcat occupies port 8080, MySQL occupies port 3306, Oracle occupies port 1521, etc.).
3) Dynamic / private ports: 49152 ~ 65535.
The combination of port number and IP address yields a network Socket: Socket.
2.4 network protocol
2.4.1 TCP protocol
3.5.1.1 overview
There are two very important protocols in the transport layer protocol:
(1) Transmission control protocol (TCP)
(2) 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: orderly: the order will not be disordered,
Reliable. Data can be sent only after the connection is successful,
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
2.4.1.2 Socket
- 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
2.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. 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.
2.4.1.4 server
The working process of the server program includes the following four basic steps:
1. Call ServerSocket(int port): create a server-side socket and bind it to the specified port. Used to listen for client requests.
2. Call accept(): listen for connection requests. If the client requests a connection, it accepts the connection and returns the communication socket object.
3. 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.
3. Close ServerSocket and Socket object: the client access ends and the communication Socket is closed.
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
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 TCPServer { public static void main(String[] args) throws Exception { // 1 create object open port ServerSocket ss = new ServerSocket(10004); 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(); } // Open first and then close pw.close(); os.close(); skt.close(); ss.close(); System.out.println("The server is down"); } public static void test() 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")); pw.println("how are you?"); pw.println("Did you have your meal?"); pw.flush(); // Open first and then close pw.close(); os.close(); skt.close(); ss.close(); System.out.println("The server is down"); } }
2.4.1.5 client
The working process of the client Socket includes the following four basic steps:
1. Create 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.
2. 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
3. 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.
4. 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:
1.Socket(String host,int port)throws UnknownHostException,IOException: initiate a TCP connection to the server (the domain name is host and the port number is port). If it succeeds, create a socket object, otherwise an exception will be thrown. 2.Socket(InetAddress address,int port)throws IOException: initiate 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
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 TCPClient { public static void main(String[] args) throws Exception { // Create object, bind IP and port Socket skt = new Socket("127.0.0.1", 10004); // 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(); } }
2.4.2 UDP protocol
2.4.2.1 overview
UDP: fast, unreliable, packet loss and no connection
- 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, as well as 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.
2.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 - 1.
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 It starts at offset and lasts for length.
- public int getLength() returns the length of the data to be sent or received.
2.4.2.3 client
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 UDPClient { 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(); } } }
2.4.2.4 server
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.net.DatagramPacket; import java.net.DatagramSocket; public class UDPServer { 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); } } }
2.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