This article takes you to explore the mysteries of Java communication interviews: demystify the IO model, selectors and network protocols, and understand the necessary knowledge points in the interview!

Understand common TCP/UDP

TCP (Transmission Control Protocol) is a connection-oriented reliable transmission protocol. Similar to making a phone call, it improves the reliability of communication by establishing a connection and ensuring the reliable transmission of data. However, due to the need to ensure the reliability of data, the TCP protocol will increase the burden on the network, and the efficiency is relatively low.

UDP (User Datagram Protocol) is a connectionless, unreliable transmission protocol. Similar to broadcasting, the UDP protocol can realize one-to-many communication, and since there is no connection establishment and data confirmation, the transmission efficiency is relatively high. However, UDP is less reliable due to the lack of connection and confirmation mechanism.

After understanding TCP and UDP, common interview questions include TCP's three-way handshake and four-way wave. Why use a three-way handshake instead of a two-way handshake? This is because of the inherent instability of network transmission, such as network timeouts and network congestion. If only two handshakes are performed, when the server returns the second handshake to the client, it is impossible to determine whether the client has successfully established a connection. Therefore, a third handshake must be performed to ensure that the client received the connection request. Otherwise, if the client loses the connection request due to network reasons, the server will wait for the idle timeout of the connection before closing the request, which will seriously consume server resources.

The four-way wave is also the reason for the three-way handshake. Due to the instability of network transmission, it is necessary to ensure that both parties receive the disconnection request when disconnecting. In four waves, first the client sends a disconnection request, then the server sends a message confirming receipt of the request, then the server sends a disconnection request, and finally the client sends a message confirming receipt of the request to complete the connection disconnection open. This ensures that both sides handle the disconnect properly.

Understood BIO, NIO, AIO

BIO is the simplest I/O model, which uses synchronous blocking to communicate. Each client connection requires an independent thread for processing. When there are a large number of concurrent requests, the number of threads will increase sharply, resulting in increased resource consumption and performance degradation.

image

NIO is a relatively complex I/O model that uses Channel, Selector, and Buffer to achieve non-blocking communication. Through the multiplexing mechanism of Selector, one thread can be used to handle multiple client connections, thereby improving the concurrency capability. However, NIO is suitable for handling short requests. If I/O is occupied for a long time, it may cause server resource exhaustion.

image

The following is an example of implementing a simple server using NIO:

 
 

java

copy code

import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.util.Iterator; public class NioServerExample { public static void main(String[] args) throws IOException { // 创建ServerSocketChannel,并绑定端口 ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.socket().bind(new InetSocketAddress(8080)); serverSocketChannel.configureBlocking(false); // 创建Selector,并将ServerSocketChannel注册到Selector上 Selector selector = Selector.open(); serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); while (true) { // 监听事件 selector.select(); // 处理事件 Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator(); while (keyIterator.hasNext()) { SelectionKey key = keyIterator.next(); keyIterator.remove(); if (key.isAcceptable()) { // 接受客户端连接 ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel(); SocketChannel socketChannel = serverChannel.accept(); socketChannel.configureBlocking(false); socketChannel.register(selector, SelectionKey.OP_READ); } else if (key.isReadable()) { // 读取客户端数据 SocketChannel socketChannel = (SocketChannel) key.channel(); ByteBuffer buffer = ByteBuffer.allocate(1024); int bytesRead = socketChannel.read(buffer); if (bytesRead == -1) { // 客户端关闭连接 socketChannel.close(); } else { buffer.flip(); byte[] data = new byte[buffer.remaining()]; buffer.get(data); String message = new String(data); System.out.println("Received message: " + message); // 响应客户端 ByteBuffer responseBuffer = ByteBuffer.wrap("Hello, client!".getBytes()); socketChannel.write(responseBuffer); } } } } } }

AIO is simpler than NIO, but because the bottom layer needs the support of the operating system, the scope of application is relatively small. AIO is an asynchronous non-blocking I/O model. On the basis of NIO, another thread is used to process the return value of the business, so as to realize asynchronous operation.

image

The core components of JAVA NIO

The core components of JAVA NIO include buffer, channel and selector.

  • The buffer is used to store the data information that the client interacts with the server,
  • Channels are similar to streams, and each client will have an independent channel.
  • The selector is the key to the multiplexing, it finds the channel with the event and hands it off to the server thread for processing.

Through these core components, the JAVA NIO model realizes efficient non-blocking I/O operations and improves the server's concurrent processing capabilities.

image

Comparison and application of select, poll and epoll

select, poll, and epoll are three I/O multiplexing mechanisms in the Linux system. Their purpose is to enable efficient event-driven programming to select read, write, or exception events among multiple I/O operations.

A file descriptor is a record table of files opened by a maintenance process. Each open file is assigned a unique file descriptor.

  • select is one of the oldest mechanisms, which can monitor the state changes of multiple file descriptors at the same time. However, select has some disadvantages. For example, it needs to copy the file descriptor set from user space to kernel space every time it is called, which is inefficient. Also, select supports a limited number of file descriptors.
  • poll is an improved version of select, which transfers the file descriptor information to the kernel through a pollfd structure array, avoiding the problem of copying every call in select. poll also supports more file descriptors, but as the number of file descriptors increases, the performance will decrease.
  • epoll is a new mechanism introduced in the Linux 2.6 kernel, which registers and waits for events through the epoll_ctl and epoll_wait functions. epoll uses an event array to store monitored file descriptors and event status. It only needs to add the file descriptor to the event array when registering, instead of passing the entire file descriptor every time it is called like select and poll. gather. This makes epoll have higher performance in large-scale concurrency.

HTTP vs HTTPS: Understanding the Difference and Security

safety:

  • HTTP is a clear text protocol, and data is not encrypted during transmission, so it is easy to be intercepted and eavesdropped by a third party.
  • HTTPS provides higher security by encrypting and authenticating data using SSL (Secure Sockets Layer) or TLS (Transport Layer Security) protocols.

The port number:

  • HTTP uses port number 80 for communication by default
  • HTTPS uses port number 443 for communication by default

Certificate:

  • HTTPS uses digital certificates to verify the server's identity. Certificates are issued by a trusted third-party organization to ensure the identity of the communicating parties and the integrity of the data.
  • HTTP does not require the use of certificates and cannot verify the identity of the server.

The HTTPS protocol increases the computational and communication burden between the server and the client, making the server more vulnerable to stress when handling a large number of requests. Although HTTPS can provide a certain degree of security protection, it will also increase the burden on the server, making the server more vulnerable to DDoS attacks.

Summarize

By deeply exploring the mysteries of Java communication interviews, we will demystify the three I/O models (BIO, NIO, and AIO), selectors (select, poll, and epoll) and network protocols (such as HTTP and HTTPS) in Java to help you Know the essential knowledge points in the interview. These knowledge points are crucial for job seekers in network programming and system security, mastering them will lay a solid foundation for your career development!

Guess you like

Origin blog.csdn.net/wdj_yyds/article/details/131961847