Java network programming from beginner to Proficient (16): Timeout for client socket (socket)

Source: Internet
Author: User
Tags set time connection reset

The time-out (timeout) of a client socket refers to a phenomenon in which the server does not respond to the client in time due to network delay, network congestion, etc. during the client's communication through the socket and the server. After a period of time, the client throws a timeout error because it does not receive a response from the server; the time at which the client waits is the time-out.

Because one end of the production time-out error is passive, that is, the end is receiving data instead of sending data. For a client socket, only two are receiving data, one is connecting to the server, and the other is receiving data from the server after the connection server succeeds. Therefore, there are two types of client timeouts: connection Timeouts and read data timeouts .

One, connection timeout

This timeout has been used in the previous example. Only the second parameter of the Connect method can be used in the socket class to specify when a connection time-out occurs . Because connecting to the server using the Connect method, you must specify an IP and port, so an invalid IP or port will cause a connection time-out error.

Second, read the data timeout

After the successful connection of the server, the two most important things that the socket does is "receive data" and "Send data", while receiving the data may be due to network delay, network congestion and other reasons, the client has been waiting, and after waiting for a period of time, if the server has not sent data to the client, then the client socket will throw a timeout error .

We can use the Setsotimeout method of the socket class to set the time of the read data timeout , and the time is in milliseconds. This method must be called before the data is read to take effect. If you set the time-out to 0, the time-out is not used; that is, when the client disconnects from the server, it will depend entirely on the timeout setting of the service-side program. The following statement sets the read data time-out time to 5 seconds.

Socket socket = new socket (); Socket.setsotimeout (); Socket.connect (...); Socket.getinputstream (). read ();

Note that you should not set the connection timeout and read data timeout too small , if the value is too small, such as 100, may cause the server data has not been sent, the client throws a timeout error phenomenon. The following code gives an example of a test connection timeout and read data timeout .

Packagemynet;
Import java.net.*;
public class Sockettimeout { Public static void Main (string[] args){         long time1 = 0, time2 = 0; SOCKET socket = new socket (); Try{             if (Args.length < 4){                 System.out.println ("parameter Error!"); return; }
time1 = System.currenttimemillis (); Socket.connect (New Inetsocketaddress (Args[0], Integer. parseint (Args[1])), Integer.parseint (args[2])); socket.setsotimeout (Integer.parseint (args[3)); time1 = System.currenttimemillis (); Socket.getinputstream (). read (); }         catch (sockettimeoutexception e){             if  (!socket.isclosed ()  && socket.isconnected ())        &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SYSTEM.OUT.PRINTLN ("Read data timeout!");             else       &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SYSTEM.OUT.PRINTLN ("Connection timeout");                  catch  ( Exception e)         {             system.out.println (E.getmessage ());         }         finally          {             time2 = system.currenttimemillis ();              system.out.println (TIME2&NBSP;-&NBSP;TIME1);         }     }}

The main method of the Sockettimeout class requires 4 parameters: IP (domain name), port, connection timeout, read data timeout. Let's use a set of data to test this example.

Test 1 : Invalid IP time-out error raised

Execute the following command:

Java mynet. Sockettimeout 192.168.18.24 80 3000 5000

Operation Result:

Connection Timeout 3045

Note: The 192.168.18.24 is an invalid IP, and if the IP exists in the network environment, please change the other invalid IP. In this test case, the invalid IP cannot be replaced with an invalid domain name, because if the domain name is used to connect to the server, Java will first map the domain name to the appropriate IP via DNS, and if the domain name is invalid, an error will occur during the mapping process, so the program will not perform a connection server operation. Naturally, the "Connection timeout" error is not thrown.

Test 2 : Invalid port-raised timeout error

Execute the following command:

Java mynet. Sockettimeout www.ptpress.com.cn 8888 3000 5000

Operation Result:

Connection Timeout 3075

Test 3 : Read Data timeout error

Execute the following command:

Java mynet. Sockettimeout www.ptpress.com.cn 80 3000 5000

Operation Result:

Read Data Timeout! 5008

Test 4 : Sets the read data timeout to 0 the effect

Execute the following command:

Java mynet. Sockettimeout www.ptpress.com.cn 80 3000 0

Operation Result:

Connection Reset 131519

The output from the previous 3 Tests was not difficult to see, and each test case set the connection time-out and read-data timeouts to 3000 and 5000 milliseconds, respectively, and their results were not 3000 and 5000 milliseconds, but instead swung around the set timeout time. This is mainly because the output time of the system is not always the time-out period, if some time is the Java processing error, the time to output information to the console. In addition, due to the system timing error, it will also affect the accuracy of time-out. However, the time-out will always swing around the set time.

For test 4, after setting the read data time-out to 0, the Sockettimeout class passed 2 minutes (131519 milliseconds) before the connection reset error was thrown. The time to throw the error is related to the timeout setting of the service-side program, which is the result of the server-side program actively disconnecting the client network connection.

Java network programming from beginner to Proficient (16): Timeout for client socket (socket)

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.