Solution to the csocket class receive timeout Problem

Source: Internet
Author: User

 

A problem occurred several days ago. How to Handle timeout when the csocket receive is blocked. BecauseProgramSocket communication is used in multiple threads. At the beginning, the receive function is monitored regularly in the main thread. After the timeout, the communication ends. However, the problem is that the csocket object cannot be released. Therefore, you can search for a solution on the Internet to process the receive timeout directly in the thread.

Good. I found the following content, and many websites are reposted.

Configure the time-out function for csocket

Csocket operations, such as send (), receive (), and connect (), are all blocking operations, that is, they will not return until successful completion or error occurs.

In some cases, an operation may never be completed successfully. In order to wait for it to be completed, the program will have to loop forever.It is a good idea to limit a successful completion time for an operation in the program.This article discusses this issue.
One way is to design a timer that is triggered when the operation fee is too long.The key to this approach is how to handle the timer.Although the operation is "blocked", it still has the ability to process the returned message.If you use settimer to set a timer, You can intercept the wm_timer message and terminate the operation when it is generated.The main functions involved in this process are Windows API: settimer (), MFC function csocket: onmessagepending () and csocket: cancelblockingcall ().These functions can be encapsulated into your csocket class for simplicity.
Class uses three important functions:
Bool setTimeout (uint utimeout) should be called before the csocket function is called.Utimeout is measured in thousands of minutes.The following implementation is just a simple timer setting.If the timer fails to be set, false is returned.For more information, see settimer in Windows API.
Bool killtimeout () this function should be called when the operation is not completed or blocked.It deletes the timer set by setTimeout.If killtimer fails to be called, false is returned.For more information, see killtimer in Windows API.
Bool onmessagepending () is a virtual callback function that is called by the csocket class when the operation is completed.It gives you the opportunity to process the returned message.This time, we use it to check the timer set by setTimeout. If the timer times out, it calls cancelblockingcall ().See descriptions of onmessagepending () and cancelblockingcall () in the MFC documentation.Note that calling cancelblockingcall () will cause the current operation to fail. The getlasterror () function returns wsaeintr (indicating that the operation is interrupted ).
The following is an example of using this class :...

 Ctimeoutsocket sockserver;
Cacceptedsocket sockaccept;
Sockserver. Create (
777 );
Sockserver. Listen ();
// Note the following sequence:
// SetTimeout
// <Operation which might block>
// Killtimeout
If ( ! Sockserver. setTimeout ( 10000 ))
{
Assert (false );
// Error Handling... for some reason, we cocould not setup
// The timer.
}
If ( ! Sockserver. Accept (sockaccept ))
{
Int Nerror = Getlasterror ();
If (Nerror = Wsaeintr)
Afxmessagebox (
" No connections arrived for 10 seconds " );
Else
;
// Do other error processing.
}
If ( ! Sockserver. killtimeout ())
{
Assert (false );
// Error Handling... for some reason the timer cocould not
// Be destroyed... perhaps a memory overwrite has changed
// M_ntimerid?
//
}
...

The following is an exampleCode:

//  Header file
//
Class Ctimeoutsocket: Public Csocket
{
Public :
Bool setTimeout (uint utimeout );
Bool killtimeout ();
Protected :
Virtual Bool onmessagepending ();
Private :
Int M_ntimerid;
};
// End of File
//
//
// Implementation File
//
Bool ctimeoutsocket: onmessagepending ()
{
MSG;
If (: Peekmessage ( & MSG, null, wm_timer, wm_timer, pm_noremove ))
{
If (Msg. wparam = (Uint) m_ntimerid)
{
// Remove the message and call cancelblockingcall.
: Peekmessage ( & MSG, null, wm_timer, wm_timer, pm_remove );
Cancelblockingcall ();
Return False; // No need for idle time processing.
}

}
Return Csocket: onmessagepending ();
}
Bool ctimeoutsocket: setTimeout (uint utimeout)
{
M_ntimerid
= Settimer (null, 0 , Utimeout, null );
Return M_ntimerid;
}
Bool ctimeoutsocket: killtimeout ()
{
Return Killtimer (null, m_ntimerid );
}

 

I create the class and complete the code in the above way. After running the test, no effect was found! Onmessagepending does not monitor the wm_timer message.

Then I made some adjustments to the class to make the encapsulation better. Secondly, there is basically no need to make any changes to external calls. Thirdly, I want to make onmessagepending work.

In fact, the modification is very simple. It is to change both setTimeout and killtimeout to private functions, reload the receive and send functions of the csocket base class, and start and close the timer before and after sending and receiving.

 Class  Ctimeoutsocket:  Public Csocket
{
// Attributes
Public :

// Operations
Public :
Ctimeoutsocket ();
Virtual ~ Ctimeoutsocket ();

// Overrides
Public :
// Classwizard generated virtual function overrides
// {Afx_virtual (ctimeoutsocket)
Public :
Virtual Bool onmessagepending ();
Virtual Int Receive ( Void * Lpbuf, Int Nbuflen, Int Nflags = 0 );
Virtual Int Send ( Const Void * Lpbuf, Int Nbuflen, Int Nflags = 0 );
// } Afx_virtual

// Generated message map Functions
// {Afx_msg (ctimeoutsocket)
// Note-The classwizard will add and remove member functions here.
// } Afx_msg

// Implementation
Protected :
Int M_ntimerid;
Private :
Bool killtimeout ();
Bool setTimeout (
Int Ntimeout );
};

Bool ctimeoutsocket: onmessagepending ()
{
MSG;
If (: Peekmessage ( & MSG, null, wm_timer, wm_timer, pm_noremove ))
{
If (Msg. wparam = (Uint) m_ntimerid)
{
// Remove the message and call cancelblockingcall.
: Peekmessage ( & MSG, null, wm_timer, wm_timer, pm_remove );
Cancelblockingcall ();
Return False; // No need for idle time processing.
};
};
Return Csocket: onmessagepending ();
}

Int Ctimeoutsocket: receive ( Void * Lpbuf, Int Nbuflen, Int Nflags)
{
SetTimeout (
10000 );
Int Nrecv = Csocket: receive (lpbuf, nbuflen, nflags );
Killtimeout ();
Return Nrecv;
}

Int Ctimeoutsocket: Send ( Const Void * Lpbuf, Int Nbuflen, Int Nflags)
{
SetTimeout (
10000 );
Int Nsend = Csocket: Send (lpbuf, nbuflen, nflags );
Killtimeout ();
Return Nsend;
}

Bool ctimeoutsocket: setTimeout (
Int Ntimeout)
{
M_ntimerid
= Settimer (null, 0 , Ntimeout, null );
Return M_ntimerid;
}

Bool ctimeoutsocket: killtimeout ()
{
Return Killtimer (null, m_ntimerid );
}

After the modified Code is run, onmessagepending receives the wm_timer message, which correctly solves the receive blocking problem. At the same time, I only need to change the original csocket object to the ctimeoutsocket object, other code does not need to be changed.

Original article address:Http://blog.csdn.net/happyparrot/article/details/1832815

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.