www.pudn.com > antispam-addin.rar > conmunicate.cxx


// Conmunicate.cpp: implementation of the Conmunicate class. 
// 
////////////////////////////////////////////////////////////////////// 
 
#include  
#include  
#include  
 
#ifdef unix 
#include  
#include  
#include  
#endif 
 
#include "conmunicate.hxx" 
 
 
#ifdef unix 
#define INVALID_SOCKET -1 
#define SOCKET_ERROR -1 
#define INADDR_NONE 0xffffffff 
#endif 
 
 
////////////////////////////////////////////////////////////////////// 
// Construction/Conmunicate 
////////////////////////////////////////////////////////////////////// 
 
#define MAXHOSTNAME 128 
 
Conmunicate::Conmunicate() 
{ 
} 
 
Conmunicate::~Conmunicate() 
{ 
	Close(); 
} 
 
bool Conmunicate::Create(unsigned int nSocketPort, int nSocketType, char *szSocketAddress) 
{ 
	m_hSocket = socket(PF_INET, nSocketType, AF_UNSPEC); 
	if(m_hSocket == INVALID_SOCKET) 
		return false; 
 
	int bOptVal = 1; 
	int rc = setsockopt(m_hSocket, SOL_SOCKET, SO_REUSEADDR, (char*)&bOptVal, sizeof(int)); 
 
	unsigned long ulInetAddr = inet_addr(szSocketAddress); 
	if (ulInetAddr == INADDR_NONE && szSocketAddress && (strlen(szSocketAddress) > 0)) 
		return false; 
 
	m_hSockAddrIn.sin_family = PF_INET; 
	m_hSockAddrIn.sin_port = htons(nSocketPort); 
	m_hSockAddrIn.sin_addr.s_addr = ulInetAddr; 
 
	return true; 
} 
 
 
int Conmunicate::StartAccess(int major_version /* =2 */, int minor_version /* =2 */) 
{ 
	int nRc = 0; 
 
#if defined(_WINDOWS) 
	WSADATA wsa_data; 
	nRc = WSAStartup (MAKEWORD(major_version,minor_version), &wsa_data); 
#endif 
 
	return nRc; 
} 
 
 
bool Conmunicate::Connect(char *szHostAddress, unsigned int nHostPort ) 
{ 
	m_hSockAddrIn.sin_family = PF_INET; 
	m_hSockAddrIn.sin_port = htons(nHostPort); 
	m_hSockAddrIn.sin_addr.s_addr = inet_addr(szHostAddress); 
 
	if(connect(m_hSocket, (sockaddr*)&m_hSockAddrIn, sizeof(struct sockaddr)) == SOCKET_ERROR) 
		return false; 
 
	return true; 
} 
 
 
bool Conmunicate::Close() 
{ 
#if defined( unix ) 
	if(close(m_hSocket)) 
#else // windows 
	if(closesocket(m_hSocket)) 
#endif 
	 
		return false; 
 
	return true; 
} 
 
 
bool Conmunicate::Send(const void* lpBuf, int nBufLen, int nFlags) 
{ 
	int nSentLen = nBufLen; 
	int nRemainLen = nBufLen; 
		 
	while(nRemainLen > 0) 
	{ 
		if((nSentLen = send (m_hSocket, (const char *)lpBuf + nBufLen - nRemainLen, nRemainLen, nFlags)) == SOCKET_ERROR) 
		{ 
			nSentLen = 0; 
			return false; 
		} 
 
		nRemainLen -= nSentLen; 
	} 
 
	return true; 
} 
 
 
bool Conmunicate::Receive( void* lpBuf, int &nBufLen, int nFlags) 
{ 
#ifdef unix 
	nFlags |=MSG_WAITALL; 
#endif 
 
	if((nBufLen = recv(m_hSocket, (char *)lpBuf, nBufLen, nFlags)) == SOCKET_ERROR) 
	{ 
		nBufLen = 0; 
		return false; 
	} 
 
	return true; 
}