本文讲解CSocket同步操作阻塞时设置超时的解决方案。
    最近参加了中兴公司的通信软件设计大赛,开发一个模拟手机和基站信令通信的软件,遇到CSocket发送阻塞的问题,这里有一个简单的解决方案供大家参考。
    CSocket继承自CAsyncSocket,他们的不同是前者是同步套接字,后者是异步套接字,操作都是异步的。Socket中的Receive、Send 和Connect是阻塞操作,我们知道阻塞操作的特点是要么运行成功退出,要么出现错误退出,而且有的时候如果不成功,则该函数会一直阻塞,整个程序会一直等待操作的完成。
    本文提出的解决方法是通过编程限制完成操作使用的时间,设置定时,设定一定的超时时间,如果阻塞操作时间过程,则启动该超时机制。虽然操作是阻塞操作,但是我们可以处理操作中到达的消息。如果通过使用 SetTimer 设置定时器,那么可以查找 WM_TIMER 消息,并在收到该消息时终止操作。
    这种方法比较常见,也比较容易想到,网上也有很多相关的思想。设置定时的方法有::SetTimer函数,具体参加msdn。处理消息过程是CSocket中的CSocket::OnMessagePending 函数,退出阻塞的函数是CSocket中的CSocket::CancelBlockingCall 函数。我们在使用的时候往往是定义自己的CClientSocket类继承自CSocket类,这样这些函数都可以获得了。
    本人通过网上的资料得知,这种方法目前仅适用于 Visual C++ 的 1.52、1.52b、2.1 和 2.2 版本。
    相关函数如下:

BOOL SetTimeOut(UINT uTimeOut)

     调用此函数之后仅接着调用 CSocket 函数(如 Receive、Send 和 Accept)。uTimeOut 参数是以毫秒为单位指定的。之后,进行定时器的设置。如果设置定时器失败,那么函数返回 FALSE。有关详细情况,请参阅 SetTimer 函数的 Windows API 文档。

BOOL KillTimeOut()

     在完成阻塞操作后,必须调用此函数。此函数删除用 SetTimeOut 设置的定时器。如果调用 KillTimer 失败,则返回 FALSE。有关详细情况,请参阅 KillTimer 函数的 Windows API 文档。

BOOL OnMessagePending()

     这是一个虚拟回调函数,在等待操作完成时由 CSocket 类进行调用。此函数给您提供处理传入消息的机会。此实施过程检查用 SetTimeOut 调用函数设置的定时器的 WM_TIMER 消息。如果收到消息,则调用 CancelBlockingCall 函数。有关 OnMessagePending 和 CancelBlockingCall 函数详细的信息,请参阅 MFC 文档。请注意:调用 CancelBlockingCall 函数 将导致操作失败,而且 GetLastError 函数返回 WSAEINTR(表示操作中断)。

    相关实现如下:
头文件
InBlock.gif class CClientSocket : public CSocket
InBlock.gif{
InBlock.gif   //friend CClientThread;
InBlock.gif // Attributes
InBlock.gif public:
InBlock.gif   //CMCSServerDlg* m_dlgServer;
InBlock.gif   //CWinThread* m_pThread;
InBlock.gif
private:
InBlock.gif   int m_nTimerID;
InBlock.gif // Overrides
InBlock.gif public:
InBlock.gif  BOOL KillTimeOut();
InBlock.gif  BOOL SetTimeOut(UINT uTimeOut);
InBlock.gif   // ClassWizard generated virtual function overrides
InBlock.gif   //{{AFX_VIRTUAL(CClientSocket)
InBlock.gif   public:
InBlock.gif   virtual void OnReceive( int nErrorCode);
InBlock.gif   virtual void OnClose( int nErrorCode);
InBlock.gif   virtual BOOL OnMessagePending();
InBlock.gif   //}}AFX_VIRTUAL

InBlock.gif //设置超时
InBlock.gifBOOL CClientSocket::SetTimeOut(UINT uTimeOut)
InBlock.gif{
InBlock.gif  m_nTimerID = SetTimer(NULL,0,uTimeOut,NULL);
InBlock.gif   return m_nTimerID;
InBlock.gif}
InBlock.gif
//取消设置超时
InBlock.gifBOOL CClientSocket::KillTimeOut()
InBlock.gif{
InBlock.gif   return KillTimer(NULL,m_nTimerID);
InBlock.gif}
InBlock.gif
//用于CSocket函数阻塞时,如果超时,则退出该阻塞函数
InBlock.gifBOOL CClientSocket::OnMessagePending()
InBlock.gif{
InBlock.gif  MSG msg;
InBlock.gif   if(::PeekMessage(&msg, NULL, WM_TIMER, WM_TIMER, PM_NOREMOVE)) {
InBlock.gif     if (msg.wParam == (UINT) m_nTimerID) {
InBlock.gif      ::PeekMessage(&msg, NULL, WM_TIMER, WM_TIMER, PM_REMOVE);
InBlock.gif      CancelBlockingCall();
InBlock.gif       return FALSE;
InBlock.gif    };
InBlock.gif  };
InBlock.gif
   return CSocket::OnMessagePending();
InBlock.gif}

    使用这种机制的代码如下:
InBlock.gif if(!sockServer.SetTimeOut(10000))
InBlock.gif{
InBlock.gif     // 错误处理,不能建立定时
InBlock.gif }
InBlock.gif if(!sockServer.Accept(sockAccept))
InBlock.gif {
InBlock.gif       int nError = GetLastError();
InBlock.gif       if(nError==WSAEINTR)
InBlock.gif             //重传处理等等
InBlock.gif        else
InBlock.gif             //错误处理
InBlock.gif }
InBlock.gifi f(!sockServer.KillTimeOut())
InBlock.gif {
InBlock.gif    //不能取消定时,错误处理
InBlock.gif }


网上的另一种实现:
InBlock.gif // 自己计算时间的办法 OK
InBlock.gif public:
InBlock.gif         BOOL SetTimeOut(UINT uTimeOut=1000);
InBlock.gif         BOOL KillTimeOut();
InBlock.gif private:
InBlock.gif    LONGLONG m_llDtStart;
InBlock.gif    UINT    m_uTimeOut;
InBlock.gif};
InBlock.gif
/
InBlock.gif
//`AFX_INSERT_LOCATION`
InBlock.gif // Microsoft Visual C++ will insert additional declarations immediately before the previous line.
InBlock.gif
#endif // !defined(AFX_TIMEOUTSOCK_H__19897A81_4EAF_4005_91FD_DC3047725139__INCLUDED_)
InBlock.gif
     // TimeOutSock.cpp : implementation file
InBlock.gif //
InBlock.gif
#include "stdafx.h"
InBlock.gif#include "NetBroad.h"
InBlock.gif#include "TimeOutSock.h"
InBlock.gif
#ifdef _DEBUG
InBlock.gif#define new DEBUG_NEW
InBlock.gif#undef THIS_FILE
InBlock.gif static char THIS_FILE[] = __FILE__;
InBlock.gif#endif
InBlock.gif
/
InBlock.gif // CTimeOutSock
InBlock.gif
CTimeOutSock::CTimeOutSock()
InBlock.gif{
InBlock.gif
}
InBlock.gif
CTimeOutSock::~CTimeOutSock()
InBlock.gif{
InBlock.gif}
InBlock.gif

InBlock.gif // Do not edit the following lines, which are needed by ClassWizard.
InBlock.gif# if 0
InBlock.gifBEGIN_MESSAGE_MAP(CTimeOutSock, CSocket)
InBlock.gif //{{AFX_MSG_MAP(CTimeOutSock)
InBlock.gif //}}AFX_MSG_MAP
InBlock.gifEND_MESSAGE_MAP()
InBlock.gif#endif // 0
InBlock.gif
/
InBlock.gif // CTimeOutSock member functions
InBlock.gif
//设置超时
InBlock.gifBOOL CTimeOutSock::SetTimeOut(UINT uTimeOut)
InBlock.gif{    
InBlock.gif //get start cnt
InBlock.gif LARGE_INTEGER llCnt;
InBlock.gif ::QueryPerformanceCounter(&llCnt);
InBlock.gif m_llDtStart=llCnt.QuadPart;
InBlock.gif m_uTimeOut=uTimeOut;
InBlock.gif
         return TRUE;
InBlock.gif}
InBlock.gif
//删除超时参数
InBlock.gifBOOL CTimeOutSock::KillTimeOut()
InBlock.gif{
InBlock.gif m_llDtStart=0; //表明取消计时
InBlock.gif return TRUE;
InBlock.gif}
InBlock.gif
//检查是否超时间
InBlock.gifBOOL CTimeOutSock::OnMessagePending()
InBlock.gif{
InBlock.gif // TODO: Add your specialized code here and/or call the base class
InBlock.gif /*
InBlock.gif MSG msg;
InBlock.gif    if(::PeekMessage(&msg, NULL, WM_TIMER, WM_TIMER, PM_NOREMOVE))
InBlock.gif    {
InBlock.gif     if (msg.wParam == (UINT) m_nTimerID)
InBlock.gif     {
InBlock.gif        // Remove the message and call CancelBlockingCall.
InBlock.gif        ::PeekMessage(&msg, NULL, WM_TIMER, WM_TIMER, PM_REMOVE);
InBlock.gif        CancelBlockingCall();
InBlock.gif        return FALSE;    // No need for idle time processing.
InBlock.gif     };
InBlock.gif    };
InBlock.gif */

InBlock.gif if( m_llDtStart )
InBlock.gif {
InBlock.gif    LARGE_INTEGER lldtEnd;
InBlock.gif    ::QueryPerformanceCounter(&lldtEnd);    
InBlock.gif    LARGE_INTEGER llFrq;
InBlock.gif    ::QueryPerformanceFrequency(&llFrq);
InBlock.gif     double dbDealy=( double)(lldtEnd.QuadPart-m_llDtStart)*1000/llFrq.QuadPart;
InBlock.gif     if( dbDealy>m_uTimeOut )
InBlock.gif    {
InBlock.gif     CancelBlockingCall();
InBlock.gif     return FALSE;     // No need for idle time processing.
InBlock.gif    }
InBlock.gif }
InBlock.gif
InBlock.gif return CSocket::OnMessagePending();
InBlock.gif}