A brief analysis of JAVA socket timeout

Source: Internet
Author: User
Tags ack connection reset

A socket or socket (socket) is a form of software abstraction used to express the "terminal" of a connection between two machines. There is a "socket" on each machine for a particular connection, and you can imagine a virtual "cable" between them. Java has two data flow-based sockets classes: ServerSocket, which the server uses to "Listen" for incoming connections; the socket, which the client uses to initiate a connection. A listening socket can only receive new connection requests and cannot receive actual packets.

Sockets are implemented based on TCP/IP and are used to provide a service interface that accesses TCP, or the socket socket is a TCP application programming interface API that provides access to TCP services through its application layer.

In Java, we create a socket connection with the ServerSocket, Socket class, and the result from the socket is a InputStream and OutputStream object to treat the connection as an IO stream object. The IO stream can read data from the stream or write the data into the stream, and the read/write IO stream will have an abnormal ioexception generation.

The socket base is TCP-based, so the timeout for the socket and the TCP timeout are the same. The socket read-write buffer is discussed below, followed by the connection establishment timeout, read-write timeout, and nested exception captures for Java socket programming and a sample grab for a timeout example program.

1 socket read-write buffer

Once a socket instance is created, the operating system allocates buffers for it to hold the data that is received and to be sent.

Java can set the read-write buffer size-setreceivebuffersize (int size), setsendbuffersize (int size).

Writing data to the output stream does not mean that the data has actually been sent, they are simply copied to the send buffer queue sendq, or the flush () method is raised in the socket's outputstream, nor does it guarantee that the data can be sent immediately to the network. The real data is sent by the operating system's TCP stack module from the buffer to send data to the network to complete.

When there is data coming from the network, the TCP stack module receives the data and puts it into the receive buffer queue RECVQ, and the input stream inputstream the data out of the RECVQ through the Read method.

2 Socket Connection Setup Timeout

The socket connection establishment is a TCP-based connection establishment process. The TCP connection needs to be completed by 3 handshake messages, a synchronous SYN message needs to be sent when the TCP connection is started, and then the acknowledgment message is Syn+ack, and then the ACK is sent. TCP connection is closed by 4 waves to complete, the side of the active shutdown TCP connection to send fin messages, waiting for the other party's confirmation message, the passive closed side also send fin message, wait for confirmation message.

There is a fixed-length connection queue waiting on one end of the TCP connection request, and the connection in the queue has been accepted by TCP (that is, the three handshake has been completed), but it has not yet been accepted by the application layer. TCP accepts a connection by placing it in the connection queue, and the application layer accepts the connection to remove it from the queue. The application layer can set the backlog variable to indicate the maximum length of the connection queue, which is the maximum number of connections that have been accepted by TCP waiting for the application tier to accept.

When a connection request SYN arrives, TCP determines whether to accept the connection. If there is space in the queue, the TCP module confirms the SYN and completes the connection creation. However, the application layer will not know the new connection until the third message in the three handshake is received. If the queue has no space, TCP will ignore the received Syn.

If the application tier does not accept connections that have been accepted by TCP in a timely manner, these connections may fill the entire connection queue, and new connection requests may not respond and time out. If a connection request SYN Send, after a period of time not received confirmation SYN+ACK,TCP will retransmit the connection request Syn two times, each retransmission time interval doubled, in the specified time still not received syn+ack,tcp will abandon this connection request, connection establishment timed out.

The JAVA socket connection establishment timeout is the same as TCP, and if the TCP three handshake times out when the connection is established, the socket connection establishment also expires. You can set the time-out for the socket connection setting-

Connect (socketaddress endpoint, int timeout)

If the connection is not established successfully within the timeout, the timeoutexception exception is thrown. If the value of timeout is less than three handshake times, then the socket connection will never be established.

Different application tiers have different connection establishment processes, the socket connection is established like TCP-just three handshake to complete the connection, but some applications need to interact with a lot of information to successfully establish a connection, such as the Telnet protocol, after the TCP three handshake is completed, after the option negotiation is required, The Telnet connection was established.

3 Socket Read timeout

If there is no data in the input buffer queue RECVQ, the read operation will block and suspend the thread until new data arrives or an exception occurs. Call Setsotimeout (int timeout) to set the time-out period, and if there is still no data at the time-out, read throws a sockettimeoutexception, and the program needs to catch the exception. However, the current socket connection is still valid.

If the opponent process crashes, the other machine restarts abruptly, the network disconnects, and the read on this side is blocked, it is very important to set the timeout time, otherwise the thread that calls read will always hang.

The TCP module puts the received data into the RECVQ until the application layer invokes the Read method of the input stream for reading. If the RECVQ queue is filled, TCP notifies the other party not to continue sending the data based on the sliding window mechanism, which stops receiving data sent from the peer until the recipient application calls the Read method of the input stream to free up space.

4 Socket Write Timeout

The write timeout for the socket is based on a TCP timeout retransmission. Time-out retransmission is an important mechanism for TCP to ensure data reliability transmission, the principle is to send a data message after the start of a timer, in a certain period of time if not received the acknowledgement of the sending message, then resend the message. If the message is still not confirmed after resending multiple times, send a reset message rst and then close the TCP connection. The time difference between the first data message sending and the reset message transmission is approximately 9 minutes, which means that the connection is closed if no acknowledgement message is received within 9 minutes. However, this value is different depending on the implementation of the TCP protocol stack.

If the send side calls write to continuously write out the data until the SENDQ queue is filled. If the Write method is called when the SENDQ queue is full, write is blocked until SENDQ has new free space, that is, until some bytes are transferred to the RECVQ of the receiver socket. If the RECVQ queue is also filled at this point, all operations will stop until the receive side calls the Read method to transfer some bytes to the application.

When the socket's write sends data, if the network cable disconnects, the peer-to-peer process crashes, or the peer machine restarts, the TCP module will retransmit the data and finally close the connection when it times out. The next time you call write again, it causes an exception to exit.

Socket write timeout is based on the TCP protocol stack time-out retransmission mechanism, generally do not need to set the write timeout time, nor provide this method.

5 Double nested exception captures

If the ServerSocket, socket construct fails, you only need to capture this construct failure exception without calling the Close method of the socket to free the resource (you must ensure that the construction fails without leaving any resources that need to be purged) because the socket internal resource is not successfully allocated. If the construct succeeds, you must enter a try finally statement block to call close to release the socket. Please refer to the example procedure below.

[Java:nogutter]View Plaincopy
  1. Import java.net.*;
  2. Import java.io.*;
  3. Public class Socketclienttest
  4. {
  5. public static final int PORT = 8088;
  6. public static void Main (string[] args) throws Exception
  7. {
  8. InetAddress addr = Inetaddress.getbyname ( "127.0.0.1");
  9. Socket socket = new socket ();
  10. Try
  11. {
  12. Socket.connect ( new inetsocketaddress (addr, PORT), 30000);
  13. Socket.setsendbuffersize (100);
  14. BufferedWriter out = new BufferedWriter ( new OutputStreamWriter (Socket.getoutputstream ()));
  15. int i = 0;
  16. While ( true)
  17. {
  18. SYSTEM.OUT.PRINTLN ( "Client Sent---hello * * * *" + i++);
  19. Out.write ( "Client Sent---hello * * * *" + i);
  20. Out.flush ();
  21. Thread.Sleep ( 1000);
  22. }
  23. }
  24. finally
  25. {
  26. Socket.close ();
  27. }
  28. }
  29. }

[Java:nogutter]View Plaincopy
  1. Import java.io.*;
  2. Import Java.net.ServerSocket;
  3. Import Java.net.Socket;
  4. Public class Socketservertest
  5. {
  6. public static final int PORT = 8088;
  7. public static final int BACKLOG = 2;
  8. public static void Main (string[] args) throws IOException
  9. {
  10. ServerSocket Server = new ServerSocket (PORT, BACKLOG);
  11. System.out.println ("started:" + server);
  12. Try
  13. {
  14. Socket socket = server.accept ();
  15. Try
  16. {
  17. BufferedReader in = new BufferedReader ( new InputStreamReader (Socket.getinputstream ()));
  18. String info = null;
  19. While (info = in.readline ()) = null)
  20. {
  21. SYSTEM.OUT.PRINTLN (info);
  22. }
  23. }
  24. finally
  25. {
  26. Socket.close ();
  27. }
  28. }
  29. finally
  30. {
  31. Server.close ();
  32. }
  33. }
  34. }

Execute the above program, after the program runs for a while, disconnect the network connection between the client and server, and output the following on the machine:

Output on the server:

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 output after---->> Disconnected network connection

Output on the client:

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

Client process hangs after---->> disconnected network connection

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 HELLO6 is sent to the server side, the network connection is disconnected, and the server side cannot receive any data and hangs. The client side continues to send data, in fact Hello7, Hello8, Hello9, hello10 are copied to the SENDQ queue, and the Write method returns immediately. When the client's SENDQ queue is filled, the Write method is blocked. After sending the message Hello7, the TCP module expires the retransmission without receiving acknowledgement, and then the TCP connection is closed after several retransmissions, and the blocked write method returns unexpectedly.

By grasping the package tool, we can see the retransmission message over time.

http://blog.csdn.net/zdwzzu2006/article/details/7748006

JAVA Socket Timeout Analysis (GO)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.