How to set socket connect timeout in java

Source: Internet
Author: User
Tags set socket socket connect

1. Set the flag bit to Non-blocking mode, and call the connect function in Non-blocking mode.
2. call connect. Normally, the TCP three-way handshake takes some time, but the non-blocking call will return an error if it cannot be completed immediately. Therefore, EINPROGRESS is returned here, indicates that the connection is established but is not completed.
3. fd_set rset and fd_set
Set the current interface bit (using FD_ZERO (), FD_SET () macro), and set the timeout time (struct
Timeval * timeout)
4. Call select (socket, & rset, & wset, NULL, timeout)
If the return value is 0, the connection times out.
If you set a timeout value greater than 75 seconds, there is no need to do so, because the connection timeout limit in the kernel is 75 seconds.

I think everyone knows the socket components in network programming. socket is the set interface. In the set interface programming, when we mention the concept of timeout, we can suddenly think of three: sending timeout, receiving timeout, and select timeout (note:
The select function is not only used to set the interface, but is usually used in programming.) This timeout cannot be set when you connect to the target host. However, under normal circumstances, the timeout is long, and connect is a blocking method. A host cannot be connected and can't be tolerated when connect returns. If your program wants to try to connect multiple hosts, i'm afraid you will not be able to stand it when you encounter multiple hosts that cannot be connected. If you think you have mastered this method, you don't have to look at it again. If you still don't know it, I 'd like to share it with you. This article is an example of a program in Linux, but the same is true in Windows. It is nothing more than changing the name of several functions.
In Linux, there should be two methods to set timeout for connect. One is some parameters of the system. I don't want to talk about this method because I don't know it clearly: P, which is not implemented by programming. Another method is to implement connect timeout in disguise. I want to talk about this method, in principle:
1. Establish socket
2. Set the socket to non-blocking mode.
3. Call connect ()
4. Use select () to check whether the socket descriptor is writable (note that it is writable)
5. Determine the connect () result based on the result returned by select ()
6. Set the socket to the blocking mode (if your program does not need to use the blocking mode, this step is saved, but generally the blocking mode is used, which is easy to manage)
If you are familiar with network programming, you will know how to write your program as soon as I talk about this process. Here is a piece of program I wrote for your reference only.

The code is as follows: Copy code
/******************************
* Time out for connect ()
* Write by Kerl W
******************************/
# Include <sys/socket. h>
# Include <sys/types. h>
# Define TIME_OUT_TIME 20 // connect timeout time 20 seconds
Int main (int argc, char ** argv)
{
..................
Int sockfd = socket (AF_INET, SOCK_STREAM, 0 );
If (sockfd <0) exit (1 );
Struct sockaddr_in serv_addr;
......... // Fill the serv_addr structure with the server address
Int error =-1, len;
Len = sizeof (int );
Timeval tm;
Fd_set set;
Unsigned long ul = 1;
Ioctl (sockfd, FIONBIO, & ul); // sets the non-blocking mode.
Bool ret = false;
If (connect (sockfd, (struct sockaddr *) & serv_addr, sizeof (serv_addr) =
-1)
{
Tm. TV _set = TIME_OUT_TIME;
Tm. TV _uset = 0;
FD_ZERO (& set );
FD_SET (sockfd, & set );
If (select (sockfd + 1, NULL, & set, NULL, & tm)> 0)
{
Getsockopt (sockfd, SOL_SOCKET, SO_ERROR, & error, (socklen_t *) & len );
If (error = 0) ret = true;
Else ret = false;
} Else ret = false;
}
Else ret = true;
Ul = 0;
Ioctl (sockfd, FIONBIO, & ul); // Set it to blocking mode
If (! Ret)
{
Close (sockfd );
Fprintf (stderr, "Cannot Connect the server! N ");
Return;
}
Fprintf (stderr, "Connected! N ");
// The package sending and receiving operations can also be performed below
...............
}

The above code snippet is for reference only and provides some tips for beginners. It mainly uses several functions: select,
Ioctl,
You can find related information for getsockopt. I will not describe it here. You just need to tap a man in linux.
<Function name> You can see its usage.
In addition, I need to note that, although we use ioctl to set the set interface to non-blocking mode, select itself is blocked, and the blocking time is the time-out from the call of select
The timeval structure variable pointed to by the pointer of the last timeval type parameter. The timeval structure consists of a number of seconds and a member representing the number of microseconds (long type, generally, we can set the number of seconds to 0 (note: 1 Second equals 1 million microseconds ). Another parameter worth mentioning in the select function is the fd_set variable pointer we used above. Before the call, this variable contains the delimiters to be checked by the select statement. After the call, it is writable to the above program, we can use the macro FD_ISSET to check whether a descriptor is in it. Because I only have one set of interface descriptors here, I didn't use the FD_ISSET macro to check whether the sockfd is in the set after the select call. In fact, I need to add this judgment. However, I used getsockopt to check whether the set of interfaces is actually connected, because we just used select in disguise to check whether it is connected, in fact, the select statement checks whether it is writable. For writable statements, it indicates writable when any of the following three conditions is met:
1) the number of available control bytes in the sending buffer of the set interface is greater than or equal to the current value at the low tide of the sending buffer of the set interface, or I) the set interface is connected, or ii) connection is not required for the set of interfaces (in UDP mode)
2) the write half of the connection is closed.
3) There is a set of interface errors to be processed.
In this way, we need to use the getsockopt function to obtain some information about the current interface to determine whether it is actually connected. When there is no connection, what error can be returned, of course, I did not mark so many states in the program, but simply said that they can be connected/not connected.
Next I will talk about the testing results of this program. I tested in three cases:
1. Normal network of the target machine
You can connect to the target host and successfully send and receive packets in blocking mode.
2. Network disconnection of the target machine
After waiting for the set timeout time (20 seconds in the preceding program), it is displayed that the target host cannot be connected.
3. Disconnect the network of the target machine before running the program, and restore the network of the target machine within the timeout period.
Before the network connection of the target host is restored, the program waits for a while. After the target host is restored, the program displays that the target host is successfully connected, and the packet sending and receiving tasks can be completed in blocking mode.
The test results in the above cases show that this method of setting the connect timeout is completely feasible. I encapsulated this timeout-based connect into my own class library and used it in a monitoring and control system. So far, the operation has been normal. The connection timeout of this programming implementation is a bit better than the method of modifying system parameters because it is only used in your program without affecting the system.

Related Article

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.