Java source code analysis and interview questions-ServerSocket source code and interview questions

This series of related blog, Mu class reference column Java source code and system manufacturers interviewer succinctly Zhenti
below this column is GitHub address:
Source resolved: https://github.com/luanqiu/java8
article Demo: HTTPS: // GitHub. com / luanqiu / java8_demo
classmates can look at it if necessary)

Java source code analysis and interview questions-ServerSocket source code and interview questions

In the
previous section, we learned about Socket. In this article, let ’s take a look at the server socket API: ServerSocket. After this article, we can connect the client socket and the server socket in series to make a real network communication. demo now.

Type 1 attribute

The main function of ServerSocket is to serve as a socket on the server side, accept the information transmitted from the client socket, and pass the response back to the client. Its properties are very simple, as follows:

private boolean created = false;// 已创建
private boolean bound = false;// 绑定
private boolean closed = false;// 已关闭
// 底层的功能都依靠 SocketImpl 来实现
private SocketImpl impl;

ServerSocket and Socket, the bottom layer depends on the capabilities of SocketImpl, and the realization of the underlying capabilities of SocketImpl are basically implemented by native methods.

2 Initialization

Initialization can be divided into two categories: parameterless constructors and parameterized constructors.

  1. The parameterless constructor is relatively simple, only specifying SocketImpl as the SocksSocketImpl class;
  2. There are several forms of initialization for parametric constructors. Let's take a look at the source code of the constructor with the most parameters.
public ServerSocket(int port, int backlog, InetAddress bindAddr) throws IOException {
    // 默认是 SocksSocketImpl 实现
    setImpl();
    // 端口必须大于 0,小于 65535
    if (port < 0 || port > 0xFFFF)
        throw new IllegalArgumentException(
                   "Port value out of range: " + port);
    // 最大可连接数如果小于1,那么采取默认的 50
    if (backlog < 1)
      backlog = 50;
    try {
        // 底层 navtive 方法
        bind(new InetSocketAddress(bindAddr, port), backlog);
    } catch(SecurityException e) {
        close();
        throw e;
    } catch(IOException e) {
        close();
        throw e;
    }
}

The input port refers to the local port that ServerSocket needs to bind to.

Entering the backlog refers to the maximum length of the server to accept the client connection queue. It should be noted here that this does not limit the number of client connections. We have done experiments under the JDK8 version. We set the server backlog to 1, and slow down the processing speed of the server. When a concurrent request comes from the server, it is not the second request to refuse the connection. In our actual work, it is best not to use backlog to limit the number of client connections.

Another point to note is that when the backlog is less than 1, the backlog will be set to the default 50.

The input InetAddress represents the ip address.

3 bind

The main function of the bind method is to bind the ServerSocket to a local port. This method is only used when we initialize the ServerSocket with a parameterless constructor. If a parameterized constructor is used, it is already bound to during initialization The local port is up.

With a parameterless constructor, generally we use it like this:

// 进行初始化
ServerSocket serverSocket = new ServerSocket();
// 进行绑定
serverSocket.bind(new InetSocketAddress("localhost", 7007));

4 accept

The accept method is mainly used by ServerSocket to accept the socket from the client. If there is no request from the client at this time, the method will block all the time. If there is a timeout set by the setSoTimeout method, then the accept will only be within the timeout. Blocking, an exception will be thrown after the timeout.

The bottom of the bind and accept methods are both implemented by native methods, so we will not look at the source code.

5 Interview questions

5.1 Tell me about your understanding of Socket and ServerSocket?
A : Both of us can be called sockets. The bottom layer is based on the TCP / UDP protocol. The socket encapsulates the bottom layer protocol, which makes it more convenient for us to use. Socket is often used on the client side to the server side For requesting data and accepting responses, ServerSocket is often used on the server side to accept and process requests from clients. Both of its underlying uses rely on the native methods of subclasses of SocketImpl.

5.2 Tell me about SO_TIMEOUT in SocketOptions?
Answer : The SocketOptions class has many attribute settings, such as SO_TIMEOUT, SO_LINGER, etc. You can talk about your own understanding of these questions. You can refer to "Socket Source Code and Interview Questions" for the analysis of various attributes.

5.3 When constructing Socket, can I choose TCP or UDP? How should I choose?
Answer : Yes, Socket has a three-parameter constructor. The third parameter indicates whether you want to use TCP or UDP.

5.4 Does TCP have a mechanism to automatically detect whether the server is alive? Is there a better way?
Answer : Yes, we can activate this function through the setKeepAlive method. If there is no communication between the client and the server socket within two hours, TCP will automatically send a keepalive probe to the server. It is predicted that there are three situations on the server. :

  1. The server uses the expected ACK reply, indicating that everything is normal;
  2. The server responds with RST, indicating that the server is in a crash or restart state and terminates the connection;
  3. No response from the server (will try multiple times), indicating that the socket has been closed.

However, we do not recommend using this method. We can start a scheduled task ourselves and regularly access the special interface of the server. If the data returned by the server is consistent with expectations, the server is alive.

to sum up

Socket and ServerSocket have nothing to say in terms of source code. Basically, they are some settings. The underlying implementation is a native method, but the interviewer will extend from this to some knowledge of network protocols, because this is beyond the scope of this column. By the way, interested students can Baidu by themselves.

Published 40 original articles · won praise 1 · views 5353

Guess you like

Origin blog.csdn.net/aha_jasper/article/details/105609548