socketx.cpp

来自「这是有关邮件操作的源程序代码,是很有用的源代码」· C++ 代码 · 共 98 行

CPP
98
字号
// SOCKETX.CPP -- Extension of the CSocket class
//

#include "stdafx.h"
#include "socketx.h"


#ifdef _DEBUG
#undef THIS_FILE
static char BASED_CODE THIS_FILE[] = __FILE__;
#endif

IMPLEMENT_DYNAMIC(CSocketX, CSocket)

int CSocketX::Send(LPCTSTR lpszStr, UINT uTimeOut, int nFlags)
{
	// 如果有TimeOut时间限制
	if (uTimeOut > 0)
		SetTimeOut(uTimeOut);

	// 调用基类方法
	int nRet = CSocket::Send(lpszStr, strlen(lpszStr), nFlags);

	// 如果曾经设置过TimeOut
	if (uTimeOut > 0)
	{
		KillTimeOut();
		// 如果超时,返回错误
		if (GetLastError() == WSAEINTR)
			SetLastError(WSAETIMEDOUT);
	}
	return nRet;
}


int CSocketX::Receive(CString& str, UINT uTimeOut, int nFlags)
{
	static char szBuf[256];//静态缓冲区
	memset(szBuf, 0, sizeof(szBuf));//清空

	// 如果有TimeOut时间限制
	if (uTimeOut > 0)
		SetTimeOut(uTimeOut);

	//调用基类方法
	int nRet = CSocket::Receive(szBuf, sizeof(szBuf), nFlags);

	// 如果曾经设置过TimeOut
	if (uTimeOut > 0)
	{
		KillTimeOut();
		// 如果超时,返回错误
		if (nRet == SOCKET_ERROR)
		{
			if (GetLastError() == WSAEINTR)
				SetLastError(WSAETIMEDOUT);
		}
	}

	//填入收到的字符
	str = szBuf;
	return nRet;
}

BOOL CSocketX::OnMessagePending() 
{
	MSG msg;

	// 监视定时器消息,并不把它从消息队列取出
	if(::PeekMessage(&msg, NULL, WM_TIMER, WM_TIMER, PM_NOREMOVE))
	{
		// 如果等待时间超过TimeOut
		if (msg.wParam == (UINT) m_nTimerID)
		{
			// 删除消息
			::PeekMessage(&msg, NULL, WM_TIMER, WM_TIMER, PM_REMOVE);
			// 取消这次连接
			CancelBlockingCall();
			return FALSE;
		}
	}
	// 调用基类方法
	return CSocket::OnMessagePending();
} 


BOOL CSocketX::SetTimeOut(UINT uTimeOut) 
{ 
	m_nTimerID = SetTimer(NULL,0,uTimeOut,NULL);
	return m_nTimerID;
} 


BOOL CSocketX::KillTimeOut() 
{ 
	return KillTimer(NULL,m_nTimerID);
} 

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?