Knowledge Base Nr: 00232 socketsupport.cpp - http://www.swe-kaiser.de

MFC: Erweiterungen der MFC-Sockets

  
#ifndef SOCKETSUPPORT_H
#define SOCKETSUPPORT_H

#define MAXLEN 4096

#include <afxsock.h>

class CSocketSupport : public CAsyncSocket
{
public:
CSocketSupport(bool bLineMode = true);
virtual ~CSocketSupport();

void SetLineMode(bool bLineMode) { m_bLineMode = bLineMode; }

virtual void OnError(const char* lpszError);
virtual void OnSocketReceive(const char* lpszData, int nDataLen);

virtual void OnConnect(int nErrorCode);
bool IsConnected() { return m_bInitialized; }

protected:
bool m_bLineMode;
bool m_bInitialized;

char m_cBuffer[MAXLEN];
int m_nCurr;

virtual void OnReceive(int nErrorCode);
virtual void OnClose(int nErrorCode);
};

#endif // SOCKETSUPPORT_H

//////////////////////////////////////////////////////////////////////

#include <afxwin.h> // MFC core and standard components
#include <afxsock.h> // MFC socket extensions
#include "SocketSupport.h"

CSocketSupport::CSocketSupport(bool bLineMode)
{
m_bLineMode = bLineMode;
m_bInitialized = false;
m_nCurr = 0;
ZeroMemory(m_cBuffer, sizeof(m_cBuffer));
}

CSocketSupport::~CSocketSupport()
{
}

void CSocketSupport::OnError(const char* lpszError)
{
MessageBox(NULL, lpszError, "SocketClient", MB_OK);
}

void CSocketSupport::OnSocketReceive(const char* lpszData, int nDataLen)
{
MessageBox(NULL, lpszData, "SocketClient", MB_OK);
}

void CSocketSupport::OnConnect(int nErrorCode)
{
CAsyncSocket::OnConnect(nErrorCode);

if (nErrorCode!=0)
{
m_bInitialized = false;
OnError("Failed to connect to server.");
Close();
}
else
{
m_bInitialized = true;
}
}

void CSocketSupport::OnReceive(int nErrorCode)
{
CAsyncSocket::OnReceive(nErrorCode);

if (nErrorCode != 0)
{
m_bInitialized = false;
OnError("Network connection failed.");
Close();
}
else
{
char szTmp[MAXLEN+1] = {0};

int nLen = Receive(szTmp, sizeof(szTmp));
if ((nLen == SOCKET_ERROR) || (nLen == 0))
return;

if (!m_bLineMode)
{
// send it to the app
OnSocketReceive(szTmp, nLen);
}
else
{
if (m_nCurr + nLen >= MAXLEN) // too much data, lose it
m_nCurr=0;

for (int i=0; i<nLen; i++)
m_cBuffer[m_nCurr++] = szTmp[i];

// find a newline
while (1)
{
for (i=0; i<m_nCurr; i++)
{
if ((m_cBuffer[i] == '\n') || (m_cBuffer[i] == '\r'))
{
//m_cBuffer[i] = 0;
i--;
break;
}
}

if (i == m_nCurr) // no newline
return;

// found a newline: copy that much of m_cBuffer into szTmp
int nPosNewLine = i;
for (i=0; i<=nPosNewLine; i++)
szTmp[i] = m_cBuffer[i];
szTmp[i] = 0; // null terminate it
nLen = strlen(szTmp);

// send it to the app
if (nLen)
OnSocketReceive(szTmp, nLen);

int n=0;
for (i=nPosNewLine+1; i<=m_nCurr; i++)
{
m_cBuffer[n] = m_cBuffer[i];
n++;
m_nCurr--;
}
}
}
}
}

void CSocketSupport::OnClose(int nErrorCode)
{
CAsyncSocket::OnClose(nErrorCode);

if (m_bInitialized && nErrorCode!=0)
OnError("Connection to SocketClient server lost.");

m_bInitialized = false;
}