Socket timeout Analysis

Socket timeout Analysis

  The socket or socket (Socket) is a piece of software in the form of an abstract, the expression for the "end" of a connection between two machines. For a particular connection, each machine has a "socket", imagine there is a virtual "cable" between them. There are two classes based on the JAVA data stream sockets: ServerSocket, servers use to "listen" for incoming connections; Socket, once the initial client connection with it. Listening socket can only receive a new connection request can not be received actual packet.

  Socket is based on TCP / IP implementation, which is used to provide access to a TCP service interface, or a TCP socket socket application programming interface API, through which the application layer can access the services provided by TCP.

In JAVA, we create a ServerSocket, Socket class a socket connection, the results obtained from the socket is a InputStream and OutputStream objects to be connected as an IO stream object treat. Can be read from the stream by the data stream IO or writing data to the stream, the stream will write IO IOException exception generated.

  Socket underlayer is based on TCP, the TCP socket timeout and timeouts are the same. The following discussion first socket write buffer, followed by a discussion connection establishment timeout, timeouts and write JAVA socket programming nested exception capture and capture illustrative example of a time-out procedure.

1 socket read and write buffers

  Once you have created a socket instance, the operating system to receive and store data buffer to be sent will be assigned.

 

 

  JAVA read buffer size may be provided -setReceiveBufferSize (int size), setSendBufferSize (int size).

  Write data to the output stream does not mean that the data has actually been sent, but they are copied to the transmit buffer queue SendQ, is to call the flush () method on OutputStream Socket, we can not guarantee that the data can be sent to the network immediately. An actual data transmission is taken by the operating system protocol stack module TCP data transmitted from the buffer to the network to complete.

  When data arrive from the network, TCP protocol stack module receives the data and placed in the receive buffer queue RecvQ, retrieve data from the input stream InputStream RecvQ by the read method.

2 socket connection establishment timeout

  socket connection is established based on the TCP connection establishment process. TCP connections require packets through a 3-way handshake to complete, began to establish synchronization needs to send a SYN packet is a TCP connection, and then waits for an acknowledgment message SYN + ACK, and finally sends an acknowledgment message ACK. TCP connection closed by four wave to complete one active close the TCP connection transmits a FIN packet, wait for an acknowledgment packet; passive closed one FIN packet is also transmitted, and then waits for an acknowledgment message.


  Waiting TCP connection request queue connected to one end of a fixed length, connected to the TCP queue has been accepted (i.e., three-way handshake has been completed), but has not been accepted by the application layer. Accepts a TCP connection is placed in the connection queue, the application layer connection is accepted it is removed from the queue. The application layer to indicate that the maximum length of the connection queue backlog variables by setting, accepted by TCP already maximum number of connections awaiting acceptance application layer.

  When a connection request arrives SYN, TCP determines whether to accept the connection. If there is space in the queue, TCP SYN module will confirm and complete the establishment of the connection. But only in the application layer in the third three-way handshake packets received you will know this new connection. If the queue is no space, TCP will ignore the received SYN.

  If the server does not get to accept a TCP connection has been accepted, these connections may be filled its queue, the new connection request time out may not be responding. If a connection request SYN transmission, no acknowledgment is received after a period of time SYN + ACK, TCP will retransmit the connection request SYN twice, each time doubling the retransmission interval, still not received within a predetermined period of time SYN + ACK, TCP discards the connection request, the connection is established on overtime.

  JAVA Socket timeouts, and TCP connection establishment are the same, if the TCP three-way handshake to establish a connection timeout, then it leads to the establishment of the Socket connection timed out. You can set the timeout Socket connection establishment -

connect(SocketAddress endpoint, int timeout)

If within the timeout, the connection is not established successfully, an exception is thrown in TimeoutException. If the value is less than the three-way handshake timeout time, then the Socket connection will never be established.

  Different application layers have different connection establishment process, Socket connection establishment and TCP the same - only need three-way handshake to complete the connection, but some applications require the interaction lot of information to successfully establish a connection, such as Telnet protocol, three-way handshake is completed in TCP later, after the need for option negotiation, Telnet connection was established.

3 socket read timeout

  If the input buffer queue RecvQ no data, read operations would have been blocked and suspended thread until new data arrives or an exception is generated. Call setSoTimeout (int timeout) can set the timeout to timeout if there is no data yet, read will throw a SocketTimeoutException, procedures need to catch this exception, but the current socket connection is still valid.

  If the other process crashes, the other machine suddenly restarted, disconnected from the network, the end of the read would have been blocked down, then set the time-out is very important, otherwise the call will always read the thread hangs.

  TCP module converts the received data into RecvQ until the application layer calls the input stream to read the read method. If the queue is filled RecvQ, then notify TCP sliding window mechanism according to the other do not continue to transmit data, the UE stops receiving end from the transmitted data until the recipient application calls the read method of the input stream vacated space.

4 socket write timeout

  Write socket timeout is based on the TCP retransmission timeout. Retransmission timeout TCP is an important mechanism to ensure the reliability of data transmission, the principle is to start a timer after sending a data message, if not acknowledged ACK packets sent in a certain time, then re-send packets Wen. If after re-sent multiple times, still no confirmation message, it sends a reset packet RST, and then closes the TCP connection. Initial data packet and the time between sending a reset message transmission difference of about 9 minutes, that is to say if the packet is not confirmed within 9 minutes, it closes the connection. But this value is based on a different stack implementation of the TCP protocol and different.

  If the sender call write data is continuously written until the queue is filled SendQ. If you call the write method in SendQ queue is full, then write will be blocked until SendQ until there is a new free space, that is, until the number of bytes transmitted to the receiver in the socket RecvQ. If at this time RecvQ queue has been filled, all operations are stopped until the receiving end of some calls the read method of transmitting bytes to the application.

  When the transmission data write Socket if the cable is disconnected, the remote end of the machine or process crash restart, TCP module retransmits the data, and finally close the connection timeout. Next time as then call write will cause an exception and exit.

  Socket write timeout timeout retransmission mechanism is based on the TCP protocol stack, generally do not need to set write timeout, it did not provide such a method.

5 double nested exception caught

   If ServerSocket, Socket construction fails, only just failed to capture the abnormal structure without the need to call the close method of the socket to release resources (must be guaranteed not to leave any resources need to be cleared after construction fails), because then the socket word internal resources are not allocated successfully. If the construction is successful, you must enter a try finally statement block close call in the release of the socket. Please refer to the following example procedures.


import java.net.*; import java.io.*; public class SocketClientTest { public static final int PORT = 8088; public static void main( String[] args ) throws Exception { InetAddress addr = InetAddress.getByName( "127.0.0.1" ); Socket socket = new Socket(); try { socket.connect( new InetSocketAddress( addr, PORT ), 30000 ); socket.setSendBufferSize(100);

  BufferedWriter out = new BufferedWriter( new OutputStreamWriter( socket.getOutputStream() ) );
  int i = 0;
  
  while( true )
  {
    System.out.println( "client sent --- hello *** " + i++ );
    out.write( "client sent --- hello *** " + i );
    out.flush();
    
    Thread.sleep( 1000 );
  }
}
finally
{
  socket.close();
}

}
}

 

import java.io.*; import java.net.ServerSocket; import java.net.Socket; public class SocketServerTest { public static final int PORT = 8088; public static final int BACKLOG = 2; public static void main( String[] args ) throws IOException { ServerSocket server = new ServerSocket( PORT, BACKLOG ); System.out.println("started: " + server); try { Socket socket = server.accept(); try { BufferedReader in = new BufferedReader( new InputStreamReader( socket.getInputStream() ) ); String info = null;

    while( ( info = in.readLine() ) != null )
    {
      System.out.println( info );
    }
  }
  finally
  {
    socket.close();
  }
}
finally
{
  server.close();
}

}
}

 

  Performing the above procedure, after a while the program runs, the disconnection between the client and server network connection, on the machine output is as follows:

 

Server on the output:

Echoing:client sent -----hello0

Echoing:client sent -----hello1

Echoing:client sent -----hello2

Echoing:client sent -----hello3

Echoing:client sent -----hello4

Echoing:client sent -----hello5

Echoing:client sent -----hello6

 

No data is output after the network connection is disconnected ---- >>

 

Client on the output:

socket default timeout = 0

socket = Socket[addr=/10.15.9.99,port=8088,localport=4691]

begin to read

client sent --- hello *** 0

client sent --- hello *** 1

client sent --- hello *** 2

client sent --- hello *** 3

client sent --- hello *** 4

client sent --- hello *** 5

client sent --- hello *** 6

client sent --- hello *** 7

client sent --- hello *** 8  

client sent --- hello *** 9

client sent --- hello *** 10

 

 ---- >> disconnected from the network after a client process is suspended

 

java.net.SocketException : Connection reset by peer: socket write error

    at java.net.SocketOutputStream.socketWrite0( Native Method )

    at java.net.SocketOutputStream.socketWrite( SocketOutputStream.java:92 )

    at java.net.SocketOutputStream.write( SocketOutputStream.java:136 )

    at sun.nio.cs.StreamEncoder.writeBytes( StreamEncoder.java:202 )

    at sun.nio.cs.StreamEncoder.implFlushBuffer( StreamEncoder.java:272 )

    at sun.nio.cs.StreamEncoder.implFlush( StreamEncoder.java:276 )

    at sun.nio.cs.StreamEncoder.flush( StreamEncoder.java:122 )

    at java.io.OutputStreamWriter.flush( OutputStreamWriter.java:212 )

    at java.io.BufferedWriter.flush( BufferedWriter.java:236 )

    at com.xtera.view.SocketClientTest.main( SocketClientTest.java:99 )

 

  When the server-side hello6 is transmitted to the network connection is disconnected, then the server side can not receive any data pending. client terminal continues to transmit data, in fact hello7, hello8, hello9, hello10 SendQ are copied into the queue, write method returns immediately. Once the client queue is filled SendQ, write method will be blocked. After the TCP module sends packets hello7, we did not receive acknowledgment timeout retransmission, retransmit several times after closing the TCP connection, while causing abnormal write method returns blocked.

  Through packet capture tool, we can see that the timeout retransmission packets.

 

 

 

Published 13 original articles · won praise 78 · Views 450,000 +

Guess you like

Origin blog.csdn.net/bluehawksky/article/details/100556021