Java Network Programming [] Socket client configuration (timeout | port complex | Nagle algorithm | heartbeat mechanism | close connection mechanism | Buffer Size | weight setting performance | emergency data set)



I set the read timeout



1. Set Socket timeout, the timeout is not practical concept for setting the timeout time-dependent operation of the blocking, the blocking connection requires two operations the TCP :

  • ① connecting the server operation;
  • ② server waiting to read data sent to the client;

Connection time can be set individually, there is provided a read timeout;

2. Unit: ms (MS);

3. Set a non-timeout 0, when the object associated with Socket InputStream input stream performs read () operation, which is blocked for the timeout time, if this time is exceeded has not received any data, will throw abnormal;

socket.setSoTimeout(3000);


II Socket reuse port bindings



Sets whether multiplexed address and port number Socket bound: setReuseAddress( true );

socket.setReuseAddress(true);

Socket connection is established, bind the local IP address and port number before use, after using this port number, 2 minutes allowed to be used again; After the settings, you can after the connection is closed immediately use the local IP address and port number;



III Open Nagle algorithm (dip package)



1. premise: a TCP data transmission, the receiver will have received feedback data;

2. Example: If the client transmits 1 byte of data to the server, the server needs to feed back ACK information data than the size of the ACK transmission command is even larger, which is higher than the actual consumption to be consumed by data transmission;

3. Nagle algorithm introduced: In order to save the above, there was the Nagle algorithm;

  • ① server-side processing: The principle is the receiving side to the data, if the data is small, then multiple pieces of data received, along with the feedback information is then transmitted back to the terminal;
  • ② client processes: corresponding client is treated after a data transmission, will wait for the server-side feedback, and this time if there are new data to be sent, then the data will be cached, waiting in front of the data after transmitting the feedback information back to the data sender sent all cached; thus appeared in the case of the stick package;

4. Nagle Algorithm benefits: the Nagle algorithm effectively reduces the amount of data due to send small amounts of data, while a large amount of ACK loopback packet; optimize network bandwidth;

In case of need low latency is required to close the algorithm, the algorithm can cause data packets stick occurs;

socket.setTcpNoDelay(true);


IV heartbeat mechanism



Set up setKeepAlive(true)after the results: if the TCP connection is not within two hours of data transfer, the client sends a heartbeat packet will be sent to the server message, if the client does not receive feedback information server, the TCP connection has been considered disconnect, the client will throw an exception information;

//在长时间 ( 2 小时 ) 没有数据交互 , 是否需要发送心跳包确认连接
socket.setKeepAlive(true);


V connecting closing process



1. Connection closing process: for processing the behavior of the connection is closed manner, call setSoLingerfunction is provided;

2. Close note: When object calls the close method Close Socket connection, there may also buffer data is not sent, this method is that part of the buffer for processing data;

3. setSoLingerPrototype:

    /**
     * Enable/disable {@link SocketOptions#SO_LINGER SO_LINGER} with the
     * specified linger time in seconds. The maximum timeout value is platform
     * specific.
     *
     * The setting only affects socket close.
     *
     * @param on     whether or not to linger on.
     * @param linger how long to linger for, if on is true.
     * @exception SocketException if there is an error
     * in the underlying protocol, such as a TCP error.
     * @exception IllegalArgumentException if the linger value is negative.
     * @since 1.1
     * @see #getSoLinger()
     */
    public void setSoLinger(boolean on, int linger) throws SocketException

4. setSoLingerParameter analysis:

  • Boolean ON ①: the TCP connection processing function is turned off, the default is off (false);
  • ② int linger: After calls close Socket methods require blocking of data waiting for transmission buffer time, in milliseconds;

The default state: If boolean onset to false, no cache data connection process, the call will immediately close off the connection, the underlying system will send the remaining output stream buffer data, the transmission data buffer is connected to each other; if not set false It will produce blocking operation;

6. Turn off the connection process: (true, 20 is) setSoLinger case, if the set boolean onparameter is true, int lingerthe parameter set equal to the parameter a is greater than 0, then when it is closed, blocking linger milliseconds, then if there is buffer data, will It is discarded, directly connected to the other end of the transmission command, the timeout wait without passing through;

Timeout waiting for the data to reach the other side and the maximum waiting time (MSL) return;

7. Turn off the connection process (not blocked): setSoLinger( true , 0 )where, if set to 0, then the consequences are not blocked, the system does not take over the output stream buffer data immediately discarded, sending command RST to the other;



VI Socket urgent data set reserved



//设置紧急数据是否内敛 , 默认情况时 false 关闭的 ; 
socket.setOOBInline(true);

1. Emergency Data: emergent data is data sent Socket object by calling sendUrgentData; the process parameter is an int value, only the lowest 8 bits are valid;

2. Emergency transparent characteristic data: data and the emergent data in the upper layer was isolated by default, such as a client to a server transmits emergency data, the server usual normal data reception processing, which does not affect the data receiving and processing, and also I do not know the client sends urgent data;

3. To receive urgent data: urgent data if the server sends the client wants to receive, you need to get set up before the Socket input stream socket.setOOBInline(true), in order to receive data, urgent data to read;

4. An emergency data: setOOBInline Sets whether the urgent data restrained, false by default when closed;

The application scenarios: using the emergency packet data as a heartbeat;

An emergency is not recommended data introverted, may affect the accuracy of the actual data;



VII Socket set the buffer size



1. The buffer size comprises setting two buffers:

  • ① send buffer settings:
socket.setSendBufferSize(64 * 1024 * 1024);
  • ② receive buffer is provided;
socket.setReceiveBufferSize(64 * 1024 * 1024);

2. The effect of buffer: Buffer Size 32 KB default, the buffer size is not to wait until there is only 32 KB of data transmission and reception, but if the transmission and reception of data is greater than 32 KB, such as 33 KB, it will split the data is divided into two packages, 32 KB and 1KB, then transmit and receive operations;

Note that settings must be set before connection, during connection set invalid;



VIII Socket connection performance parameters



1. Socket object calls setPerformancePreferencesa method, set performance parameters of the connection; connection has the following three performance parameters:

  • ① connection time;
  • ② round-trip delay;
  • ③ the bandwidth;

2. Set the weight is not specific performance parameters: the value is not set specific parameters, but the performance of the connection weights of the weight, which is required for high performance;

3. Connect Time: If the Socket connection is very frequent, a data transfer connection, immediately disconnect, at this time compare the value of the connection time performance, this time the first parameter can be set to 10, the latter two parameters set to 1 indicating connection time focusing properties;

//设置 连接时间 性能参数较重要
socket.setPerformancePreferences(10, 1, 1);

4. Round Trip Delay: If you are developing online server, this time is the delay value, this time the second parameter may be set to a comparatively high weight;

//设置 往返延迟 性能参数较重要
socket.setPerformancePreferences(1, 10, 1);

5. Bandwidth: If you are developing audio and video servers, bandwidth-conscious, then the third parameter needs to be set to a higher weight;

//设置 带宽 性能参数较重要
socket.setPerformancePreferences(1, 10, 1);

6. Performance latency and bandwidth above are mutually exclusive, low latency, it means a very small package will be sent once, its low bandwidth, high latency, and every time it has accumulated a lot of data to send, its bandwidth correspondingly increased;

7. Prototype:

    /**
     * Sets performance preferences for this socket.
     *
     * <p> Sockets use the TCP/IP protocol by default.  Some implementations
     * may offer alternative protocols which have different performance
     * characteristics than TCP/IP.  This method allows the application to
     * express its own preferences as to how these tradeoffs should be made
     * when the implementation chooses from the available protocols.
     *
     * <p> Performance preferences are described by three integers
     * whose values indicate the relative importance of short connection time,
     * low latency, and high bandwidth.  The absolute values of the integers
     * are irrelevant; in order to choose a protocol the values are simply
     * compared, with larger values indicating stronger preferences. Negative
     * values represent a lower priority than positive values. If the
     * application prefers short connection time over both low latency and high
     * bandwidth, for example, then it could invoke this method with the values
     * {@code (1, 0, 0)}.  If the application prefers high bandwidth above low
     * latency, and low latency above short connection time, then it could
     * invoke this method with the values {@code (0, 1, 2)}.
     *
     * <p> Invoking this method after this socket has been connected
     * will have no effect.
     *
     * @param  connectionTime
     *         An {@code int} expressing the relative importance of a short
     *         connection time
     *
     * @param  latency
     *         An {@code int} expressing the relative importance of low
     *         latency
     *
     * @param  bandwidth
     *         An {@code int} expressing the relative importance of high
     *         bandwidth
     *
     * @since 1.5
     */
    public void setPerformancePreferences(int connectionTime,
                                          int latency,
                                          int bandwidth)
发布了252 篇原创文章 · 获赞 1013 · 访问量 168万+

Guess you like

Origin blog.csdn.net/han1202012/article/details/100528521