Java interview summary summary, including Java key knowledge, as well as common open source framework, welcome to read. The article may have wrong place, because individual knowledge is limited, welcome everybody big guy to point out! The article continues to be updated at……
ID The title address 1 Design Mode Interview Questions (Most comprehensive summary of interview questions) Juejin. Cn/post / 684490… 2 Java Basics (most comprehensive interview questions) Juejin. Cn/post / 684490… 3 Java Set interview Questions (the most comprehensive interview questions) Juejin. Cn/post / 684490… 4 JavaIO, BIO, NIO, AIO, Netty Interview Questions (Most comprehensive summary of interview questions) Juejin. Cn/post / 684490… 5 Java Concurrent Programming Interview questions (most comprehensive interview questions) Juejin. Cn/post / 684490… 6 Java Exception Interview Questions (The most comprehensive interview Questions) Juejin. Cn/post / 684490… 7 Java Virtual Machine (JVM) Interview Questions Juejin. Cn/post / 684490… 8 Spring Interview Questions (the most comprehensive interview questions) Juejin. Cn/post / 684490… 9 Spring MVC Interview Questions (The most comprehensive interview Questions) Juejin. Cn/post / 684490… 10 Spring Boot Interview Questions (Most comprehensive summary of interview questions) Juejin. Cn/post / 684490… 11 Spring Cloud Interview Questions (The most comprehensive interview questions) Juejin. Cn/post / 684490… 12 Redis Interview Questions (most comprehensive summary of interview questions) Juejin. Cn/post / 684490… 13 MyBatis Interview Questions (most comprehensive interview questions) Juejin. Cn/post / 684490… 14 MySQL Interview Questions (most comprehensive interview questions) Juejin. Cn/post / 684490… 15 TCP, UDP, Socket, HTTP interview questions Juejin. Cn/post / 684490… 16 Nginx Interview Questions (The most comprehensive interview Questions) Juejin. Cn/post / 684490… 17 ElasticSearch interview questions 18 Kafka interview questions 19 RabbitMQ interview questions (most comprehensive summary of interview questions) Juejin. Cn/post / 684490… 20 Dubbo Interview Questions (the most comprehensive interview questions) Juejin. Cn/post / 684490… 21 ZooKeeper Interview Questions Juejin. Cn/post / 684490… 22 Netty Interview Questions (Most comprehensive summary of interview questions) 23 Tomcat Interview Questions (The most comprehensive interview questions) Juejin. Cn/post / 684490… 24 Linux Interview Questions (Most comprehensive Summary of interview questions) Juejin. Cn/post / 684490… 25 Internet Related interview Questions (the most comprehensive summary of interview questions) 26 Internet Security Questions (Summary of the most comprehensive interview questions)
First look at the experience of a day of interviews:
The first:
- Interviewer: Tell me about the TCP three-way handshake
- Me: For the first time, the Client sets SYN to 1…… , the second Server receives…….. , the third time……..
- Interviewer: Is it hard to recite?
- I:… Yeah, it’s hard. How about I tell you four waves?
- Interviewer: don’t don’t go back to wait for notice……
- Me: “…”
The second: the heart of ten thousand grass mud horse came to the second home
- .
- Interviewer: Tell me about the TCP three-way handshake
- I (
I was thinking, come again?
) : Nothing to say, just to keep a network communication interaction normal - Interviewer: Can you be more specific?
- Me: It’s tantamount to you calling me for an interview without knowing me
- Interviewer: “dumbfounded,” something like that
- Interviewer: Tell me about TCP’s four waves
- Me: tantamount to my resignation in the last company
- Interviewer: “On second thought”, can you be more clear?
- I: I look for the boss to deal with leave office, the boss say ok, the boss then deal with leave office for me, I just can walk
- Interviewer: That makes sense!
- Interviewer: Can you tell me the difference between TCP and UDP
- Me: TCP equals to call a stranger to deal with things, UDP equals to broadcast
- Interviewer: “…” reasonable
- Interviewer: What are your salary expectations
- I: 15 k
- Interviewer: Will you be available to start next Monday?
- I:…
Let's get down to business
What is Network programming
-
The essence of network programming is data exchange between multiple computers. Data transfer itself is not that difficult, except to send data from one device to another device, and then receive feedback from another device. Network programming today is basically based on request/response, where one device sends request data to another and receives feedback from the other. In network programming, the program that initiates the connection, that is, the program that sends the first request, is called a Client. The program that waits for other programs to connect is called a Server. The client program can be started as needed, while the server needs to be started all the time in order to be able to connect at all times.
-
Take making a phone call as an example. The first person to dial the phone is like a client, and the person to answer the phone must keep the phone open like a server. Once the connection is established, data can be transferred between the client and server, and the identity of the two is equivalent. In some programs, the program has both client function and server function, the most common software is QQ, wechat this kind of software.
There are two main problems in network programming
- One is how to accurately locate one or more hosts on a network,
- The other is how to reliably and efficiently transfer data once the host is found.
-
In TCP/IP protocol, THE IP layer is mainly responsible for the location of the network host, the routing of data transmission, and the IP address can uniquely determine a host on the Internet.
-
The TCP layer provides application-oriented reliable (TCP) or unreliable (UDP) data transmission mechanism, which is the main object of network programming, generally do not need to care about the IP layer is how to deal with data.
-
The more popular network programming model is client/server (C/S) structure. That is, the two sides of the communication as a server to wait for the customer to put forward a request and respond. The client requests the service to the server when it is needed. The server is always running as a daemon, listening for network ports. Once a customer requests it, it will start a service process to respond to the customer, while it continues to listen for service ports, so that subsequent customers can be served in a timely manner.
What is the network protocol
- In order to exchange data in a computer network, it is necessary to follow some pre-agreed rules, such as the format of the exchange of data, whether to send a reply message. These rules are called network protocols.
Why layer network protocols
- Simplify problem difficulty and complexity. Since the layers are independent, we can divide the big problems into smaller ones.
- Good flexibility. When the technology of one layer changes, the other layers are not affected as long as the indirect interface relationship of the layer remains unchanged.
- Easy to implement and maintain.
- Promote standardization. When separated, the functionality of each layer can be described relatively simply
Computer network architecture
- OSI reference model
- Open System Interconnect (OSI) stands for Open System interconnection. Commonly known as the OSI reference model, it is a network interconnection model developed by ISO (International Organization for Standardization) in 1985. In order to make networking more popular, ISO introduced the OSI reference model, so that all companies can specify their networks according to the same standards, so that they can communicate with each other.
- OSI defines a seven-layer framework for network interconnection (physical layer, data link layer, network layer, transport layer, session layer, presentation layer, application layer).
-
TCP/IP reference model
-
TCP/IP Four-layer protocol (data link layer, network layer, transport layer, application layer)
- Application Layer The application layer closest to the user provides application interfaces for computer users and provides various network services for users directly. Common application layer network service protocols include HTTP, HTTPS, FTP, TELNET, etc.
- The transport layer establishes end-to-end links between hosts. The transport layer provides end-to-end reliable and transparent data transmission services for upper-layer protocols, including error control and flow control. This layer hides the details of the lower level data communication from the upper level, so that the upper level user sees only a reliable host-to-host data path that can be controlled and set by the user between the two transport entities. We usually talk about TCP UDP at this layer. The port number is the “port” here.
- Network layer This layer establishes the connection between two nodes through IP addressing, selects appropriate routing and switching nodes for packets sent by the transport layer at the source end, and correctly transmits them to the transport layer at the destination end according to the address. It is usually called the IP layer. This layer is known as the IP protocol layer. The IP protocol is the foundation of the Internet.
- The data link layer controls the transmission of the data through some procedures or protocols to ensure the correctness of the transmitted data. Implementing these procedures or protocols
hardware
And software are added to the physical circuit to form a data link,
1 TCP / UDP
1.1 What are TCP/IP and UDP
-
TCP/IP (Transmission control/Network Protocol) is a connection-oriented protocol that establishes a connection before sending data (a connection must be established between the sender and the receiver). TCP provides reliable service, that is, data transmitted over a TCP connection is not lost, is not duplicated, and arrives in sequence
-
UDP belongs to the TCP/IP protocol family. It is a connectionless protocol that does not need to establish a connection before sending data. Therefore, it has no reliability. Since no connection is required, it can be transmitted over the network in any possible path, so whether it reaches the destination, when it arrives at the destination, and the correctness of the content are not guaranteed.
1.2 Differences between TCP and UDP:
-
TCP is a connection-oriented protocol. A connection must be established before data is sent. TCP provides reliable services.
-
UDP is a connectionless protocol and does not need to establish a connection before sending data.
-
TCP communication is similar to making a phone call, confirming identity, and then starting traffic.
-
UDP communication is similar to school broadcasting, relying on broadcasting to communicate directly.
-
TCP supports point-to-point communication, while UDP supports one-to-one, one-to-many, many-to-one, and many-to-many communication.
-
TCP is byte stream oriented and UDP is packet oriented. The byte stream is byte oriented. A packet can be divided into several groups for sending. However, a UDP packet can be sent only once.
-
TCP header overhead (20 bytes) is larger than UDP header overhead (8 bytes)
-
UDP hosts do not need to maintain complex connection state tables
1.3 TCP and UDP Application Scenarios
- UDP is used in some cases with high real-time requirements, such as games, media communication and live broadcasting, even if transmission errors can be tolerated; In most other cases, HTTP uses TCP because it requires that the content transmitted be reliable and not lost
1.4 Describe TCP and UDP
-
TCP communication can be thought of as a phone call:
Li SAN (dials a number) : Hello, is that Wang Wu? Wang Wu: Hey, who are you? Li SAN: I’m Li SAN. I want to tell you something. Are you convenient now? Wang Wu: Oh, it’s convenient for me now. Go ahead. A: Did I tell you? B: Go ahead. (The connection is established, and now it’s business…)
-
UDP communication can be seen as a school broadcast:
Studio: Hey, hey! All on the playground
1.5 Analysis of TCP or UDP Application-layer protocols.
-
Protocols running over TCP:
- Hypertext Transfer Protocol (HTTP) is used for common browsing.
- HTTPS (HTTP over SSL) : the secure version of HTTP.
- File Transfer Protocol (FTP) : used for File Transfer.
- POP3 (Post Office Protocol, Version 3) is used to receive mails.
- SMTP (Simple Mail Transfer Protocol) is used to send emails.
- TELNET (Teletype over the Network) is a method of logging in to the Network through a terminal.
- Secure Shell (SSH) is used to encrypt and Secure login.
-
Protocols running on UDP:
- Boot Protocol (BOOTP) : applies to diskless devices.
- Network Time Protocol (NTP) is used for Network synchronization.
- Dynamic Host Configuration Protocol (DHCP) is used to dynamically configure IP addresses.
-
Running over TCP and UDP:
- The Domain Name Service (DNS) is used to search for addresses and forward mails.
- ECHO (ECHO Protocol), used to check errors and measure response time (running over TCP and UDP).
- Simple Network Management Protocol (SNMP) is used to collect Network information and manage networks.
- Dynamic Host Configuration Protocol (DHCP) is used to dynamically configure IP addresses.
- Address Resolution Protocol (ARP) is used to dynamically resolve Ethernet hardware addresses.
What is the Address Resolution Protocol (ARP)?
-
ARP maps IP addresses to physical addresses. Each host has an ARP cache that maps IP addresses to hardware addresses of hosts and routers on the LAN. Before sending a packet to the destination host, the source host checks whether the MAC address of the destination host is in the ARP cache. If yes, the host sends the packet directly to the MAC address. If no, the source host sends an ARP request broadcast packet to the local LAN. The host that receives the request checks whether its IP address is the same as the IP address of the destination host. If the IP address is the same, the host saves the ARP cache mapped from the source host and sends an ARP response packet to the source host. After receiving the response packet, the source host adds the MAPPING between the IP address and MAC address of the destination host before transmitting the data. If the source host does not receive any response, the ARP query fails.
-
If the host and the source host are not on the same LAN, you need to use ARP to find the hardware address of a router on the local LAN and send the packet to the router, which then forwards the packet to the next network. The next network will do the rest.
What is Network Address Translation (NAT)?
- Hosts on the Intranet need to communicate with hosts on the Internet. The NAT router translates the local IP address of the host into a global IP address, including static translation (the translated global IP address remains unchanged) and dynamic NAT.
The process from entering the address to getting the page?
- The browser queries the DNS and obtains the IP address corresponding to the domain name. The process includes searching the DNS cache of the browser, searching the DNS cache of the operating system, reading the local Host file, and querying the IP address from the local DNS server. If the domain name to be queried is included in the resources in the local configuration zone, the resolution result is returned to the client to complete domain name resolution (the resolution is authoritative). If the domain name to be queried is not resolved by the local DNS server, but the SERVER has cached the IP address mapping, invoke the IP address mapping to complete domain name resolution (the resolution is not authoritative). If the local DNS server does not cache the URL mapping, recursive or iterative queries are initiated according to its Settings.
- After obtaining the IP address corresponding to the domain name, the browser sends a request to the server to establish a link and initiate a three-way handshake.
- After the TCP/IP connection is established, the browser sends an HTTP request to the server.
- The server receives the request, processes it according to the path parameters mapped to a specific request handler, and returns the processing result and corresponding view to the browser.
- The browser parses and renders the view. If it encounters references to static resources such as JS files, CSS files and images, it repeats the above steps and requests these resources from the server.
- The browser renders the page according to the resources and data it requests, and finally presents a complete page to the user.
1.6 TCP three-way handshake
1.6.1 What is the TCP Three-way Handshake
- In network data transmission, the transport layer protocol TCP is the reliable transmission to establish a connection. The process of TCP establishing a connection is called the three-way handshake.
1.6.2 Details of the three-way handshake
- First handshake: The Client sets the SYN to 1 and randomly generates an initial sequence number (SEQ) and sends it to the Server. Then the Client enters the SYN_SENT state.
- Second handshake: After receiving the SYN=1 from the Client, the Server acknowledges the Client’s request for establishing a connection. The Server sets its SYN=1 and ACK =1 with an acknowledge number=sequence number+1 and sends a random sequence number to the Client. Enter the SYN_RCVD state.
- Third handshake: The client checks whether the acknowledge number is the serial number +1 and the ACK is 1. After checking, the client sets its ACK to 1 to generate an acknowledge number= the serial number +1 sent by the server and sends it to the server. Enter the ESTABLISHED state. After the ACK is 1 and the acknowledge number is +1, the server also enters the ESTABLISHED state. Complete the three-way handshake and establish the connection.
- To put it simply:
- The client sends the SYN to the server
- The server returns SYN,ACK
- The client sends an ACK
1.6.3 Use reality to understand the details of the three-way handshake
- The purpose of the three-way handshake is to establish a reliable communication channel. The main purpose of the three-way handshake is for both parties to confirm that their sending and receiving functions are normal.
- The first handshake: the client confirms nothing; The server confirms that the sent message is normal
- The second handshake: the customer confirms that the sending and receiving is normal, and the receiving and sending are normal. The server confirms that the receiver can receive the message correctly and the receiver can send the message correctly
- Third handshake: the customer confirms that the sending and receiving is normal, and the receiving and sending are normal. The server confirms that the sending and receiving functions are normal, while the other party sends and receives normally. Therefore, three handshakes can confirm that both the sending and receiving functions are normal.
1.6.4 Can I shake hands twice for establishing a Connection? Why is that?
- Can’t.
- An invalid connection request segment may be sent to the server. > The segment of the first connection request packet sent by the client is not lost, but is detained at a network node for a long time. As a result, it is delayed to reach the server until a certain time after the connection is released. Originally, this is an invalid packet segment. However, after the server receives the invalid connection request packet segment, it mistakenly thinks it is a new connection request sent by the client. Then the client sends a confirmation message to agree to establish a connection. Assuming that the “three-way handshake” is not used, a new connection is established as soon as the server sends an acknowledgement. Since the client does not send a connection request, it ignores the server’s confirmation and does not send data to the server. However, the server assumes that the new transport connection has been established and waits for data from the client. As a result, many of the server’s resources are wasted. The three-way handshake prevents this from happening. For example, the client does not issue an acknowledgement to the server’s acknowledgement. Since the server receives no acknowledgement, it knows that the client has not requested a connection.
- In addition, the two-handshake cannot ensure that the Client correctly receives the packet from the second handshake (the Server cannot confirm whether the Client has received the packet), nor can it ensure that the initial sequence number can be exchanged between the Client and Server.
1.6.5 Can I use the four-way handshake? Why is that?
- This one definitely works. Three handshakes will ensure a successful connection, let alone four, but will reduce transmission efficiency.
1.6.6 What If the ACK from the client fails to reach the server during the Third Handshake?
- Server: Because the Server does not receive an ACK, it resends the SYN+ACK every three seconds. (The Server resends the SYN+ACK every five times by default. After that, the connection is automatically CLOSED and the Client enters the CLOSED state.) The Client resends the ACK to the Server.
- On the Client side, two conditions occur:
- During timeout resending, if the Client sends data to the Server, the ACK header of the data is 1. Therefore, the Server reads the ACK number after receiving the data and enters the establish state
- After the Server is CLOSED, if the Client sends data to the Server, the Server responds with an RST packet.
1.6.7 What If A Client Fails after a Connection is Established?
- Each time the server receives a request from the client, it resets the timer, which is usually set to two hours. If no data is received from the client within two hours, the server sends a probe segment, which is then sent every 75 seconds. If there is no response after 10 probe packets are sent, the server assumes that the client is faulty and closes the connection.
1.6.8 What is the Initial Serial number?
- Party A of the TCP connection randomly selects A 32-bit Sequence Number (ISN) as the Initial Sequence Number (ISN) of the data to be transmitted. For example, the ISN is 1000. The data to be transmitted is numbered based on the Sequence Number: In 1001, 1002… In the three-way handshake, this initial serial number is passed to party B so that when transmitting data, PARTY B can confirm which data number is valid. At the same time, DURING data transmission, A can also acknowledge each byte received by B. If A receives B’s acknowledge number 2001, it indicates that B has successfully accepted the data with the number 1001-2000.
1.7 TCP four waves
1.7.1 What is TCP Four Waves
- In network data transmission, the transport layer protocol disconnection process is called the quadruple wave
1.7.2 Details of the four waves
- First wave: The Client sets the FIN to 1 and sends the serial number SEQ to the Server. Enter the FIN_WAIT_1 state.
- Second wave: After receiving a FIN, the Server sends an ACK=1 and acknowledge number= received serial number +1. The CLOSE_WAIT state is displayed. At this point, the client has no data to send, but can still accept the data sent by the server.
- Third wave: The Server sets the FIN to 1 and sends a sequence number to the Client. Enter the LAST_ACK state.
- Fourth wave: The Client enters the TIME_WAIT state after receiving the FIN from the server. Then set ACK to 1 and send an acknowledge number= serial number +1 to the server. After receiving the acknowledge number, the server changes to the CLOSED state and does not send data to the client. The client also enters the CLOSED state after waiting 2*MSL (maximum lifetime of packet segments). Complete four waves.
1.7.3 Using reality to Understand the details of the three-way handshake The TCP four-way wave
- The four wave disconnects to make sure all data has been transferred
- After the client finishes the conversation with the server, the client terminates the conversation by saying to the server: I want to close the connection (first wave)
- The server receives the message from the client and says: Ok, you are going to close the connection. (Second wave)
- The server then determines that it has nothing more to say to the client, and says to the client, I’m going to close the connection. (Third wave)
- The client receives the message that the server is closing the connection and says, “I received the message that you are closing the connection. (fourth wave) before closing
1.7.4 Why can’t the ACK and FIN sent by the server be merged into three waves?
- When the server receives the request for disconnection from the client, it may still have some data to send. In this case, the server replies with ACK to indicate that it has received the request for disconnection. Wait until the FIN is sent to disconnect data transfer from the server to the client.
1.7.5 What if the ACK from the server is not delivered to the client during the second wave?
- If the client does not receive an ACK confirmation, it resends the FIN request.
1.7.6 What is the Significance of the Client TIME_WAIT State?
- The ACK sent by the client to the server may be lost during the fourth wave. The TIME_WAIT state is used to resend the ACK packets that may be lost. If the Server does not receive an ACK, it resends the FIN. If the Client receives an ACK within 2MSL, it resends the ACK and waits for 2MSL to prevent the Server from resending the FIN without receiving an ACK. MSL(Maximum Segment Lifetime) : indicates the Maximum Lifetime of a Segment on the network. 2MSL is the Maximum time required for sending and replying a Segment. If the Client does not receive a FIN again until 2MSL, the Client concludes that the ACK has been successfully received and terminates the TCP connection.
2 Socket
1 What is a Socket
-
Two programs on the network exchange data through a two-way communication connection, one end of the two-way link is called a Socket. Sockets are usually used to connect clients and servers. Socket is a very popular programming interface of TCP/IP protocol. A Socket is uniquely identified by an IP address and a port number.
-
However, the protocol types supported by sockets are not only TCP/IP and UDP, so there is no necessary connection between them. In the Java environment, Socket programming mainly refers to network programming based on TCP/IP protocol.
-
Socket connection is the so-called long connection, the client and server need to connect to each other, theoretically the client and server once established the connection will not take the initiative to break, but sometimes network fluctuation is possible
-
Sockets tend to be low-level. Socket programming is rarely used directly. Socket is used more at the bottom of the framework.
2 The socket belongs to the network layer
- Socket is the intermediate software abstraction layer of communication between application layer and TCP/IP protocol family. It is a group of interfaces. In the design mode, Socket is actually a facade mode, it hides the complex TCP/IP protocol family behind the Socket interface, for the user, a simple set of interfaces is all, let the Socket to organize data to conform to the specified protocol.
3 Socket communication process
-
Based on TCP: The server initializes the Socket, binds the port, listens to the port, calls Accept to block, and waits for the client to connect. At this time, if a client initializes a Socket and then connects to the server (CONNECT), if the connection is successful, then the connection between the client and the server is established. The client sends a data request, the server receives and processes the request, then sends the response data to the client, the client reads the data, and finally closes the connection, ending an interaction.
-
Based on UDP: UDP is short for user datagram protocol and is also used for network data transmission. Although UDP is a less reliable protocol, it can sometimes be more advantageous in situations where you need to receive data quickly and tolerate minor errors. I only need to send the client, the server can receive it or not I don’t care
4 TCP Socket code example:
First run the server, then run the client,
- Server:
package com.test.io;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
//TCP Socket uses BIO for traffic: server
public class BIOServer {
Execute the following code in the main thread
public static void main(String[] args) {
//1 single thread service
ServerSocket server = null;
Socket socket = null;
InputStream in = null;
OutputStream out = null;
try {
server = new ServerSocket(8000);
System.out.println("Server started successfully, listening port 8000, waiting for client connection...");
while (true){
socket = server.accept(); // Wait for the client to connect
System.out.println("Customer connected successfully, customer information is:" + socket.getRemoteSocketAddress());
in = socket.getInputStream();
byte[] buffer = new byte[1024];
int len = 0;
// Read data from the client
while ((len = in.read(buffer)) > 0) {
System.out.println(new String(buffer, 0, len));
}
// Write data to the client
out = socket.getOutputStream();
out.write("hello!".getBytes()); }}catch(IOException e) { e.printStackTrace(); }}}Copy the code
- Client:
package com.test.io;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;
//TCP Socket: client
public class Client01 {
public static void main(String[] args) throws IOException {
// Create a socket object socket and encapsulate the IP and port
Socket socket = new Socket("127.0.0.1".8000);
// Get an output stream based on the created socket object
OutputStream outputStream = socket.getOutputStream();
// Console input is sent to the server as IO
System.out.println("TCP connection successful \n Please enter:");
while(true) {byte[] car = new Scanner(System.in).nextLine().getBytes();
outputStream.write(car);
System.out.println("TCP Socket sent successfully");
// Flush the bufferoutputStream.flush(); }}}Copy the code
Run the server first, then the client. Test result sent successfully:
5 UDP Socket code example:
Run the server first, then the client
- Server:
//UDP Socket: server
public class Server1 {
public static void main(String[] args) {
try {
//DatagramSocket specifies a UDP Socket
DatagramSocket socket = new DatagramSocket(8888);
// Byte arrays are used for data storage.
byte[] car = new byte[1024];
// The DatagramPacket class represents the DatagramPacket
DatagramPacket packet = new DatagramPacket(car, car.length);
// // Create the receive() method of DatagramPacket to receive data and wait for receiving a socket request before performing subsequent operations;
System.out.println("Waiting for UDP data transfer");
socket.receive(packet);
//packet.getLength Returns the length of the data to be sent or received.
int length = packet.getLength();
System.out.println("What's coming?" + new String(car, 0, length));
socket.close();
System.out.println("UDP Socket accepted successfully");
} catch(IOException e) { e.printStackTrace(); }}}Copy the code
- Client:
//UDP Socket: client
public class Client1 {
public static void main(String[] args) {
try {
//DatagramSocket specifies a UDP Socket
DatagramSocket socket = new DatagramSocket(2468);
// String is stored in Byte array
byte[] car = UDP Socket request may fail.getBytes();
The InetSocketAddress class encapsulates ports
InetSocketAddress address = new InetSocketAddress("127.0.0.1".8888);
// The DatagramPacket class represents the DatagramPacket
DatagramPacket packet = new DatagramPacket(car, car.length, address);
// The send() method sends packets.
socket.send(packet);
System.out.println("UDP Socket sent successfully");
socket.close();
} catch(Exception e) { e.printStackTrace(); }}}Copy the code
Run the server first, then the client. Test result sent successfully:
6 Common classes of sockets
The name of the class | Used for | role |
---|---|---|
Socket | TCP protocol | Socket class works on both Client and Server, all methods are common, this class has three main functions, check packet information, initiate a connection (Client), operation stream data (Client/Server) |
ServerSocket | TCP protocol | ServerSocket as a server, the main function is to bind and listen to a server port, for each client to establish a connection to “clone/map” a Socket object, specific data operations are completed through this Socket object, ServerSocket only concerned about how to establish a connection with the client |
DatagramSocket | The ODP agreement | The DatagramSocket class is used to represent the socket that sends and receives datagram packets. |
DatagramPacket | The ODP agreement | The DatagramPacket class is used to represent the DatagramPacket used to implement the connectionless packet delivery service. |
InetAddress | IP + port number | Java provides the InetAddress class to represent Internet Protocol (IP) addresses. Instead of a constructor, the InetAddress class provides the following two static methods to obtain instances of InetAddress: |
InetSocketAddress | IP + port number | The simplest way to connect to a server using a Socket is to use an IP address and a port. However, this method is not provided in the Socket class. Instead, InetSocketAddress, a subclass of SocketAddress, is used to create an IP address and a port number, independent of any protocol. |
3. HTTP
What is the Http protocol?
-
Http protocol is a standard for the reliable transmission of hypertext data, such as text, image, audio, and video, between the client and server. The format is called hypertext Transfer Protocol for short.
-
Http protocol belongs to the application layer, and the first layer of user access is Http
The difference between Socket and HTTP and application scenarios
-
A Socket connection is a so-called long connection. In theory, once a connection is established between the client and the server, it will not be actively broken.
-
Socket applicable scenarios: online games, continuous bank interaction, live broadcast, online video, etc.
-
An HTTP connection is a short connection, in which the client sends a request to the server, and the server responds by disconnecting the connection and waiting for the next connection
-
HTTP application scenarios: Corporate OA service, Internet service, e-commerce, office, website, and so on
What is the body of an HTTP request?
- The body of the HTTP request is the data that we send to the server first when we request data, after all, I have to tell the server what I want for the data, right
- The HTTP request body consists of: request line, request header, request data,
- Note: GIT requests do not have request bodies
-
A POST request
-
GIT requests have no request body
Find only the request line and the request header, missing the request body
What are the HTTP response packets?
-
The HTTP response is the data returned to us by the server, which must have the request body first and then the response message
-
The response message contains three parts: status line, response head field and response content entity realization
What’s the difference between HTTP and HTTPS?
-
In fact, HTTPS is from HTTP plus encryption (generally SSL secure communication line) + authentication + integrity protection
-
The difference between:
- HTTP need to get ca certificate, need money
- The port is different. HTTP is 80, https443
- HTTP is a hypertext transmission protocol, and information is transmitted in plain text. HTTPS is a secure SSL encryption transmission protocol.
- HTTP and HTTPS use completely different connections (HTTP connections are simple and stateless; HTTPS is a network protocol that uses SSL and HTTP to encrypt transmission and authenticate identity. HTTPS is more secure than HTTP.
How HTTPS works
- First, the HTTP request server generates a certificate. The client verifies the validity period and validity of the certificate, whether the domain name is consistent with the requested domain name, and the public key (RSA encryption) of the certificate.
- 2. If the verification succeeds, the client generates a random number based on the validity of the public key of the certificate. The random number is encrypted using the public key (RSA encryption).
- Thirdly, after the message body is generated, the digest of the message is encrypted by MD5 (or SHA1) algorithm, and then the RSA signature is obtained.
- 4. Send it to the server. Only the server (RSA private key) can decrypt it.
- 5. Decrypt the random number, encrypt it with AES, and use it as the key (only the client and server know the key at this time).
How many steps does a complete HTTP request go through?
HTTP communication mechanism In a complete HTTP communication process, the Web browser and the Web server will complete the following seven steps:
-
Establishing a TCP Connection
How do you make the connection? See the three hands above
-
The Web browser sends a request line to the Web server
Once the TCP connection is established, the Web browser sends a request command to the Web server. For example, GET /sample/hello.jsp HTTP/1.1.
-
The Web browser sends the request header
After the browser sends its request command, it sends some additional information in the form of a header to the Web server, and then the browser sends a blank line to inform the server that it has finished sending the header.
-
Web Server Reply
After the client sends a request to the server, the server sends back the reply, HTTP/1.1 200 OK. The first part of the reply is the version number of the protocol and the reply status code.
-
The Web server sends the reply header
Just as the client sends information about itself along with the request, the server sends data about itself and the requested document to the user along with the response.
-
The Web server sends data to the browser
After the Web server sends the header to the browser, it ends by sending a blank line to indicate that the header was sent there, and then it sends the actual data requested by the user in the format described in the Content-Type reply header.
-
The Web server closes the TCP connection
What are the common HTTP status codes?
-
The HTTP status code indicates the return result of the HTTP request from the client, identifies whether the server processes the request properly, and indicates the error of the request.
-
Categories of status codes:
category describe 1 xx: Indication message – Indicates that the request has been received and is being processed 2 xx: Success – Indicates that the request has been received, understood, and accepted successfully 3 xx: Redirect – Further action must be taken to complete the request 4 xx: Client error – The request has a syntax error or the request cannot be implemented 5 xx: Server side error – The server failed to fulfill a valid request
- Common status codes:
Status code describe 200: The request was processed normally 204: Request accepted but no resources to return 206: The client only requests a part of the resource, and the server only performs the GET method on the requested part of the resource. The corresponding packet contains the resources in the Range specified by the Content-range. 301: Permanent redirection 302: Temporary redirection 303: It has similar functionality to the 302 status code, except that when a client requests a URI, it can be redirected to another URI using the GET method 304: When a conditional request is sent, it is returned if the condition is not met, regardless of the redirect 307: Temporary redirection, similar to 302, except that the POST method is mandatory 400: The syntax of the request packet is incorrect, and the server cannot identify it 401: Request requires authentication 403: The requested resource is denied access 404: The server could not find the corresponding resource 500: Server internal error 503: The server is busy
The Http protocol has those request methods
Request way describe The GET: A request for access to a resource that has been identified by a URI (Uniform Resource Identifier) can be passed to the server through the URL POST: This method is used to transfer information to the server. It is similar to GET, but POST is recommended. PUT: When a file is transferred, the packet body contains the file content and saves it to the corresponding URI. The HEAD: The GET method is similar to the GET method but does not return the packet body. It is used to verify whether the URI has > effect. PATCH: The data the client sends to the server replaces the content of the specified document (partially replaces) TRACE: The original request packets sent by the client to the server are displayed for loopback diagnosis DELETE: To delete a file, as opposed to the PUT method, delete the file at the URI location. The OPTIONS: Query the HTTP methods supported by the URI.
The difference between GET and POST methods
-
Difference 1: Get obtains resources from the server, and POST sends data to the server.
-
Difference 2: Get transmits a small amount of data because it is limited by URL length, but it is efficient. Post transfers a large amount of data. Therefore, you can upload files only in Post mode.
-
Difference 3: Get is not secure, because get requests to send data on the URL, is visible, may reveal private information, such as passwords, etc. Post is placed at the head of the request and is safe
Comparison of HTTP versions
-
HTTP1.0 features:
- HTTP, earlier than 1.0, was a stateless, connectionless application-layer protocol.
- HTTP1.0 specifies that the browser and the server maintain a transient connection, that each browser request requires a TCP connection to the server, that the server disconnects the TCP connection as soon as it completes processing (no connection), and that the server does not track each client or record past requests (stateless).
-
New features in HTTP1.1
- The default persistent connection saves traffic. As long as neither end of the client server explicitly disconnects the TCP connection, the connection is kept and multiple HTTP requests can be sent
- Piped, a client can make multiple HTTP requests at the same time without waiting for a response
- Principle of breakpoint continuation
-
Features of the HTTP2.0 version
- Binary framing (encapsulating it with binary format encoding)
- Header compression (set up a dedicated header compression design HPACK algorithm.)
- Flow control (some flow control that sets how many bytes of a data stream are received)
- Multiplexing (the ability to send requests and responses simultaneously based on shared TCP links)
- Request priority (performance can be further optimized by optimizing interlacing and transmission order of these frames)
- Server push (where the server can send multiple responses to a client request. The server pushes resources to the client without explicit request from the client. (Major Updates)
What are symmetric and asymmetric encryption
-
Symmetric key encryption means that encryption and decryption use the same key. The biggest problem in this method is key sending, that is, how to securely send the key to the other party.
-
Asymmetric encryption refers to the use of a pair of asymmetric keys, namely a public key and a private key. The public key can be distributed freely, but the private key is known only to itself. The party that sends the ciphertext uses the other party’s public key for encryption. After receiving the encrypted information, the other party uses its own private key to decrypt the encrypted information. Asymmetric encryption can ensure security because it does not need to send the private key for decryption. But it’s very slow compared to symmetric encryption
What do cookies and sessions do for HTTP?
- HTTP protocol itself is unable to determine user identity. So you need a cookie or a session
What is a cookie
- A cookie is a file (key-value format) saved by a Web server on a user’s browser, which can contain user-related information. When the client sends a request to the server, it extracts the user information from the browser and sends it to the server through HTTP
What is a session
-
Session is the storage space allocated by the server to the session during the session between the browser and the server.
-
By default, the server sets the sessionID in the cookie of the client’s browser, and this sessionID corresponds to the cookie. The cookie transmitted by the browser during the request to the server contains the sessionID. The server obtains the information stored in the session according to the sessionID in the cookie transmission, and then determines the identity information of the session.
Cookies are different from sessions
- Cookie data is stored on the client with poor security, while session data is stored on the server with higher security
- The data saved by a single cookie cannot exceed 4K. If a session does not contain this information, it uses its own private key for decryption. Asymmetric encryption can ensure security because it does not need to send the private key for decryption. But it’s very slow compared to symmetric encryption
What do cookies and sessions do for HTTP?
- HTTP protocol itself is unable to determine user identity. So you need a cookie or a session
What is a cookie
- A cookie is a file (key-value format) saved by a Web server on a user’s browser, which can contain user-related information. When the client sends a request to the server, it extracts the user information from the browser and sends it to the server through HTTP
What is a session
-
Session is the storage space allocated by the server to the session during the session between the browser and the server.
-
By default, the server sets the sessionID in the cookie of the client’s browser, and this sessionID corresponds to the cookie. The cookie transmitted by the browser during the request to the server contains the sessionID. The server obtains the information stored in the session according to the sessionID in the cookie transmission, and then determines the identity information of the session.
Cookies are different from sessions
- Cookie data is stored on the client with poor security, while session data is stored on the server with higher security
- A single cookie cannot store more than 4K of data, and a session does not have this limit
- The session is stored on the server for a certain period of time. When the number of accesses increases, the server performance is affected. Therefore, cookies should be used in consideration of the server performance.