// CClientSocket.cpp : implementation file
#include "stdafx.h"
#include "ClientSocket.h"
// CClientSocket
CClientSocket::CClientSocket()
{
m_bConnected = FALSE;
m_strReceived = "";
m_bReceived = FALSE;
m_evtCommand = CreateEvent(NULL,FALSE,FALSE,NULL);
}
CClientSocket::~CClientSocket()
{
}
// CClientSocket member functions
BOOL CClientSocket::ConnectToServer(CString strIP, UINT nHostPort)
{
////CPRINTF(_T("CClientSocket::ConnectToServer"));
// disconnect first
if (m_bConnected)
return TRUE;
Disconnect();
if(!AfxSocketInit())
{
AfxMessageBox(_T("Failed to Initialize Sockets"),MB_OK| MB_ICONSTOP);
return FALSE;
}
// create
if (!Create())
{
AfxMessageBox(_T("create socket object failed!"));
return FALSE;
}
// connect
if (!Connect(strIP, nHostPort))
{
return FALSE;
}
m_bConnected = TRUE;
return TRUE;
}
void CClientSocket::Disconnect()
{
if (m_bConnected)
{
ShutDown();
Close();
m_bConnected = FALSE;
Sleep(200);
}
}
void CClientSocket::OnClose(int nErrorCode)
{
m_bConnected = FALSE;
m_strReceived = "";
CSocket::OnClose(nErrorCode);
}
BOOL CClientSocket::SendMsg(CString strMsg)
{
if (!m_bConnected)
return FALSE;
m_cmdLock.Lock();
CStringA strCmd = CStringA(strMsg);
if(strCmd.GetLength() != Send(strCmd,strCmd.GetLength()))
{
m_cmdLock.Unlock();
return FALSE;
}
Sleep(1);
m_cmdLock.Unlock();
return TRUE;
}
int CClientSocket::ReceiveMsg(CString &strMsg)
{
if (!m_bConnected)
return FALSE;
char szRecValue[1024] = {0};
CStringA strRecv = "";
char buf[1024] = {0};
int count = 0;
DWORD t1 = GetTickCount();
/*
count = Receive(szRecValue,1023);
if (count == SOCKET_ERROR)
{
return -1;
}*/
int nReady = 1;
//while(nReady > 0)
{
fd_set fds;
timeval timeout;
timeout.tv_sec = 5;
timeout.tv_usec = 0;
FD_ZERO(&fds);
FD_SET(this->m_hSocket, &fds);
nReady = select(0, &fds, NULL, NULL, &timeout);
if (nReady == 1)
{
memset(buf, 0, 1024);
/*len += Receive(buf, 1024 - 1);
strRecv += buf;*/
int nCount = Receive(buf, 1024 - 1);
if (nCount > 0)
{
strRecv += buf;
}
}
Sleep(1);
}
DWORD t2 = GetTickCount();
CString str = _T("");
str.Format(_T("%d"),t2-t1);
//AfxMessageBox(str);
//m_strReceived = szRecValue;
strMsg = CString(strRecv);
if(strMsg == _T(""))
return false;
m_strReceived = "";
m_bReceived = FALSE;
return TRUE;
}
void CClientSocket::DecodeString(char *chReturn, int nlength)
{
if (nlength <= 0 || !chReturn)
return;
m_strReceived = chReturn;
m_bReceived = TRUE;
SetEvent(m_evtCommand);
}
评论0
最新资源