徹底解決關於CSocket類的Receive超時的問題(轉)

lynon發表於2018-07-12

轉自: https://blog.csdn.net/enlaihe/article/details/72628700


網上有一些相關的東西,但經自己測試後,並沒有實現功能。OnMessagePending沒有監測到WM_TIMER訊息。


然後我對類進行了調整,一來使得封裝更好,二來外部呼叫基本不用做任何變化,三來希望能使OnMessagePending能夠起作用。


其實修改很簡單,就是將SetTimeOut和KillTimeOut都修改為私有函式,並過載CSocket基類的Receive和Send函式,在收發前後啟動和關閉定時器。
注意:原文中 if(::PeekMessage(&msg, NULL, WM_TIMER, WM_TIMER, PM_NOREMOVE))語句並沒有實現獲取WM_TIMER訊息的功能,後來,經過網上查詢資料
PM_NOREMOVE 修改為PM_REMOVE

標頭檔案 ClientSocket.h
#pragma once
#include "afxwin.h"
#include <afxsock.h>  
// CClientSocket 命令目標
class CTimeOutSocket : public CSocket
{
// Attributes
public:
CTimeOutSocket();
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);
virtual int SendTo(const void* lpBuf, int nBufLen,UINT nHostPort, LPCTSTR lpszHostAddress , int nFlags);
virtual int ReceiveFrom(void* lpBuf, int nBufLen,CString& rSocketAddress, UINT& rSocketPort, int nFlags);
int m_nTimerID;
private:
BOOL KillTimeOut();
BOOL SetTimeOut(int nTimeOut);
};




以下為ClientSocket.c檔案
#include "stdafx.h"
#include "ClientSocket.h"

CTimeOutSocket::CTimeOutSocket()
{
}
CTimeOutSocket::~CTimeOutSocket()
{
}
BOOL CTimeOutSocket::OnMessagePending() 
{
MSG msg;
if(::PeekMessage(&msg, NULL, WM_TIMER, WM_TIMER, PM_REMOVE))//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(5000);
int nRecv = CSocket::Receive(lpBuf, nBufLen, nFlags);
KillTimeOut();
return nRecv;
}
int CTimeOutSocket::ReceiveFrom(void* lpBuf, int nBufLen,CString& rSocketAddress, UINT& rSocketPort, int nFlags)
{
SetTimeOut(10000);
int nRecv = CSocket::ReceiveFrom(lpBuf,  nBufLen, rSocketAddress, rSocketPort,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; 
}
int CTimeOutSocket::SendTo(const void* lpBuf, int nBufLen,UINT nHostPort, LPCTSTR lpszHostAddress, int nFlags )
{
SetTimeOut(10000);
int nSend = CSocket::SendTo(lpBuf, nBufLen, nHostPort,lpszHostAddress,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);
}
經過修改的程式碼,執行後OnMessagePending得到了WM_TIMER訊息,正確解決了Receive的阻塞問題,同時我只需將原來的CSocket物件改為CTimeOutSocket物件就可以了,以上程式碼經測試可直接使用。
個人分類: 經驗分享

相關文章