Change the Accept to a non-blocking type

Source: Internet
Author: User

The program written in this project is to communicate with the remote socket, use the accept to accept the long-distance connection request, has been in the program to accept used are blocking mode, received a new connection request, the creation of a new thread processing and client communication tasks. Today, due to the need to implement the server-side set the client heartbeat cycle function, if each thread to query the database in the heartbeat packet cycle has not changed, to achieve too much trouble, instead of using the main thread to query the database stored in the heartbeat packet cycle, because the main thread needs to constantly query the database, So accept can no longer use the blocking way, the internet search a bit, did not find any method, suddenly think of my previous RECEV packet is also used to block the way, later with select to a non-blocking mode, accept can also use Select to achieve non-blocking mode. Try to change the program according to RECEV's non-blocking mode, accept successfully implemented the Non-blocking receive connection request mode.

    int maxfdp=null;
    struct Fd_set FDS;
    struct Timeval timeout={0,1};
    Fd_zero (&FDS);
    Fd_set (SOCK_SEV,&FDS);
    if (select (maxfdp,&fds,null,null,&timeout))
         cout<< "new Connection" <<endl;
		   Sock_client = Accept (Sock_sev, (SOCKADDR *) &addr_client, &naddrlen);
	       if (Invalid_socket = = sock_client)
		       std::cout << "Failed to accept." << Std::endl;
		   Std::cout << "Connection from" << Inet_ntoa (addr_client.sin_addr) << Std::endl;
		   Socketclient[i]. clientid=i;
		   Socketclient[i].socketthread=createthread (Null,0,threadread,&socketclient[i],0,socketclient[i]. ThreadID);

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: 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.