Linux client socket non-blocking connect Programming

Source: Internet
Author: User

Development and testing environment: centos, Windows Network debugging Assistant
Non-blocking mode has three purposes
1. Perform other operations at the same time with three handshakes. Connect takes a round-trip time to complete, from a LAN of several milliseconds to a WAN of several hundred milliseconds or several seconds. During this period, some other processes may be executed, such as data preparation and preprocessing.
2. Use this technology to establish multiple connections. This is common in Web browsers.
3. Because the program uses select to wait for the connection to complete, you can set a select wait time limit to shorten the connect timeout time. In most implementations, the connect timeout period is between 75 seconds and several minutes. Sometimes programs want to wait for a certain period of time to end. Using non-blocking connect can prevent blocking for 75 seconds. This is especially necessary in multi-threaded network programming. For example, there is an application that uses a thread to establish socket communication with other hosts. If the thread is used to block connect and remote communication, when there are hundreds of concurrent threads, all the threads are blocked due to network latency. The blocked threads do not release system resources. When the number of blocked threads exceeds a certain number at the same time, the system no longer allows the creation of new threads (each process can produce limited threads due to process space). If non-blocking connect is used, the connection failure will take a short wait time using select, if no connection is available, the thread immediately stops releasing resources to prevent program crash due to a large number of thread blocking.
Currently, the general idea of Connect non-blocking programming is:
After a TCP set of interfaces is set to non-blocking, connect calls connect and returns an einrpocess error in the errno variable provided by the system. At this time, the TCP three-way handshake continues. Then, you can use the select function to check whether the connection is established successfully. The following experiment provides a common example based on UNIX Network Programming and network programming. After a lot of tests, we found that there are many methods that are not applicable in Linux.
I first gave a step-by-step analysis of important source code, and finally gave a complete non-blocking source code for connect.
1. Enter the socket structure, including the remote IP address. The communication port is as follows :*/
Struct sockaddr_in serv_addr;
Serv_addr.sin_family = af_inet;
Serv_addr.sin_port = htons (9999 );
Serv_addr.sin_addr.s_addr = inet_addr ("58.31.231.255"); // convert inet_addr to the network byte order
Bzero (& (serv_addr.sin_zero), 8 );
// 2. Establish a Socket socket:
If (sockfd = socket (af_inet, sock_stream, 0) =-1)
{
Perror ("socket creat error ");
Return 1;
}
// 3. Set the socket to non-blocking mode.
Flags = fcntl (sockfd, f_getfl, 0); // obtain the current state of the created sockfd (non-blocking)
Fcntl (sockfd, f_setfl, flags | o_nonblock); // set the current sockfd to non-blocking
/* 4. establish a connect connection. At this time, the socket is set to non-blocking. After connect is called,-1 is returned no matter whether the connection is established or not, and errno (including errno. h can be used directly) is set to einprogress, indicating that the TCP three-way handshake is still in progress. If errno is not einprogress, it indicates that the connection is incorrect and the program ends.
When the client and server are on the same host, the connect return ends immediately and returns 0; no waiting is required. Therefore, the Select wait function is skipped using the Goto function, directly go to the processing section after the connection. */
If (n = connect (sockfd, (struct sockaddr *) & serv_addr, sizeof (struct sockaddr) <0)
{
If (errno! = Einprogress) return 1;
}
If (n = 0)
{
Printf ("Connect completed immediately ");
Goto done;
}
/* 5. set the wait time. Use the select function to wait for the connect function that is being connected to the background. Here, you must note that the select function is used to listen to whether the socket descriptor is readable or writable. If only writable, the connection is successful, you can perform the following operations. If the descriptor is both readable and writable, there are two types of situations. The first case is the socket connection error (Do not ask why, this is what the system requires, when reading and writing data, it may be that after the connect connection is successful, the remote host closes the connection close (socket). The second case is that the connect connection is successful, and the socket read buffer gets the data sent by the remote host. You need to determine whether an error has occurred by calling the getsockopt (sockfd, sol_socket, so_error, & error, & Len); function return value after the connect connection, here, there is a portability problem. If an error occurs in Solaris,-1 is returned, but 0 may be returned in other systems. first, I implemented it by the source code of UNIX network programming. As follows :*/
Fd_zero (& rset );
Fd_set (sockfd, & rset );
Wset = rset;
Tval. TV _sec = 0;
Tval. TV _usec = 300000;
Int error;
Socklen_t Len;
If (n = select (sockfd + 1, & rset, & Wset, null, & tval) <= 0)
{
Printf ("time out connect error ");
Close (sockfd );
Return-1;
}
If (fd_isset (sockfd, & rset) | fd_isset (sockfd, & West ))
{
Len = sizeof (error );
If (getsockopt (sockfd, sol_socket, so_error, & error, & Len) <0)
Return 1;
}
/* I tested it here. According to the UNIX Network Programming description, when a network error occurs, getsockopt returns-1, return-1, and the program ends. If the network is normal, 0 is returned, and the program continues to run.
However, in Linux, no matter whether an error occurs on the network or not, getsockopt always returns 0 without-1, indicating that there are still some minor differences between Linux and UNIX network programming. This Code does not work when the socket descriptor is readable and writable. No network faults can be detected.
The method I tested is that when connect is called, sleep (2) sleeps for 2 seconds, and the network assistant is disconnected using the two seconds. At this time, select returns 2, it indicates that the set of interfaces are readable and writable, and should be caused by network connection errors.
At this time, getsockopt returns 0 and does not work. Gets the value of errno, which indicates einprogress. No enotconn is returned in UNIX network programming. einprogress indicates that the network is being connected.
In view of this situation, three other methods are proposed in UNIX network programming. These three methods are also common non-blocking connect examples on the network:
A. Call connect again. If the error message "errno" is "eisconn" is returned, the connection is successful, indicating that the connect operation was successful. Otherwise, the operation fails. The Code is as follows :*/
Int connect_ OK;
Connect (sockfd, (struct sockaddr *) & serv_addr, sizeof (struct sockaddr ));
Switch (errno)
{
Case eisconn: // connect OK
Printf ("Connect OK/N ");
Connect_ OK = 1;
Break;
Case ealready:
Connect_0k =-1
Break;
Case einprogress: // is connecting, need to check again
Connect_ OK =-1
Break;
Default:
Printf ("Connect fail err = % d/N", errno );
Connect_ OK =-1;
Break;
}
/* As shown in the program, the value of connect_ OK is treated as follows based on the returned value of errno called again. connect_ OK is 1 to continue other operations; otherwise, the program ends.
However, I tested this method in Linux. When an error occurs, the socket Descriptor (sockfd in my program) becomes readable and writable, but after the second call of connect, errno does not return the eisconn, nor does it return the connection failure error. It is still einprogress. When the network does not fail, the second time you use the connect connection, it also returns einprogress, therefore, you cannot determine whether the connection is successful by connecting again.
B. in UNIX network programming, the READ function is used. If the READ function fails, connect fails. The returned errno indicates the cause of the failure, but this method does not work in Linux, when the socket descriptor in Linux is readable and writable, read returns 0 without setting errno as an error.
C. in UNIX network programming, the getpeername function is used. If the connection fails, after the function is called, The errno function is used to determine whether the first connection is successful, but I have tried it, no matter whether the network connection is successful or not, errno has not changed. It is einprogress and cannot be determined.
Sadly, even if you call the getpeername function, the getsockopt function still does not work.
In summary, since neither of the Methods knows whether non-blocking connect is successful, I directly send the message when the descriptor is readable and writable, and determine whether the result is successful by obtaining the server return value. (If the server design does not send data, it will be sad .)
For the sake of portability, getsocketopt is recommended for programming on UNIX networks. However, the return value is used instead of the return value.
6. Use select to view the received descriptor. If it is readable, the data is read and the program ends. When receiving data, you must first assign a new value to the descriptor for the previous rset, because the SELECT statement will be cleared for the rset. After the SELECT statement is called, if the socket is not readable, then, rset is set to zero in select. Therefore, if rset is used in the program, it is best to assign a value to rset again during use.
The program is as follows :*/
Fd_zero (& rset );
Fd_set (sockfd, & rset); // if the previous SELECT statement uses rset, it is best to assign a value again.
If (n = select (sockfd + 1, & rset, null, null, & tval) <= 0)
{
Close (sockfd );
Return-1;
}
If (recvbytes = Recv (sockfd, Buf, 1024, 0) =-1)
{
Perror ("Recv error! ");
Close (sockfd );
Return 1;
}
Printf ("receive num % d/N", recvbytes );
Printf ("% s/n", Buf );
*/

Source of the original article (Click here)

 

Attachment:

Linux client socket non-blocking connect programming (source code)
The complete non-blocking connect code is as follows:
Int main (INT argc, char ** argv)
{
Int sockfd, recvbytes, res, flags, error, N;
Socklen_t Len;
Fd_set rset, Wset;
Struct timeval tval;
Tval. TV _sec = 0;
Tval. TV _usec = 300000;
Struct sockaddr_in serv_addr;
Char * senddata = "1234567890"; // sending string
Char Buf [1024] = "/0"; // receives the buffer
// Create a socket Descriptor
If (sockfd = socket (af_inet, sock_stream, 0) =-1)
{
Perror ("socket create failed ");
Return 1;
}
Serv_addr.sin_family = af_inet;
Serv_addr.sin_port = htons (9999 );
Serv_addr.sin_addr.s_addr = inet_addr ("58.31.231.255 ");
Bzero (& (serv_addr.sin_zero), 8 );
Flags = fcntl (sockfd, f_getfl, 0 );
Fcntl (sockfd, f_setfl, flags | o_nonblock); // set to non-blocking
If (RES = connect (sockfd, (struct sockaddr *) & serv_addr, sizeof (struct sockaddr) <0)
{
If (errno! = Einprogress)
{
Return 1;
}
}
// If the server and client are on the same host, some environments will return 0 if the socket is set to non-blocking.
If (0 = res) goto done;
Fd_zero (& rset );
Fd_set (sockfd, & rset );
Wset = rset;
If (RES = select (sockfd + 1, null, & Wset, null, & tval) <= 0)
{
Perror ("Connect Time Out/N ");
Close (sockfd );
Return 1;
}
Else
{
Len = sizeof (error );
Getsockopt (sockfd, sol_socket, so_error, & error, & Len );
If (error)
{
Fprintf (stderr, "error in connection () % d-% s/n", error, strerror (error ));
Return 1;
}
}
Done:
If (n = Send (sockfd, senddata, strlen (senddata), 0) =-1)
{
Perror ("send error! ");
Close (sockfd );
Return 1;
}
If (n = select (sockfd + 1, & rset, null, null, & tval) <= 0) // rset has not been used and does not need to be reset to sockfd
{
Perror ("receive time out or connect error ");
Close (sockfd );
Return-1;
}
If (recvbytes = Recv (sockfd, Buf, 1024, 0) =-1)
{
Perror ("Recv error! ");
Close (sockfd );
Return 1;
}
Printf ("receive num % d/N", recvbytes );
Printf ("% s/n", Buf );
}

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.