Program/C & C++

MFC를 이용한 범용 서버 소켓 작성

너구리V 2011. 7. 13. 23:11
// Server socket


#define UM_ACCEPT (WM_USER+10)

class CServerSocket : public CSocket {
public:
void Init(CWnd *pWnd, int nPortNum);

protected:
CWnd *m_pWnd;
virtual void OnAccept(int nErrorCode);
};

void CServerSocket::Init(CWnd *pWnd, int nPortNum) {
m_pWnd = pWnd;
Create(nPortNum);
Listen();
}

void CServerSocket::OnAccept(int nErrorCode) {
m_pWnd->SendMessage(UM_ACCEPT);
CSocket::OnAccept(nErrorCode);
}

// Data socket
#define UM_DATARECEIVE (WM_USER+11)
class CData; // Forward declaration

class CDataSocket : public CSocket {
public:
CDataSocket();
virtual ~CDataSocket();

void Init(CWnd *pWnd);
void Send(CData *pData);
void Receive(CData *pData);
void operator << (CData &data); void operator >> (CData &data);
void Flush();

CArchive *m_pArchiveIn;
CArchive *m_pArchiveOut;

protected:
CWnd *m_pWnd;
CSocketFile *m_pFile;

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

void CDataSocket::Init(CWnd *pWnd) {
m_pWnd = pWnd;
m_pFile = new CSocketFile(this);
m_pArchiveIn = new CArchive(m_pFile, CArchive::load);
m_pArchiveOut = new CArchive(m_pFile, CArchive::store);
}

void CDataSocket::Receive(CData *pData) {
if (m_pArchiveIn != NULL)
pData->Serialize(*m_pArchiveIn);
}

void CDataSocket::operator >> (CData &data) {
&nbsp; Receive(&data);
}

void CDataSocket::Send(CData *pData) {
if (m_pArchiveOut != NULL)
pData->Serialize(*m_pArchiveOut);
}

void CDataSocket::Flush() {
if (m_pArchiveOut != NULL)
m_pArchiveOut->Flush();
}

void CDataSocket::operator << (CData &data) {
&nbsp; Send(&data);
Flush();
}

void CDataSocket::OnReceive(int nErrorCode) {
  m_pWnd->SendMessage(UM_DATARECEIVE);
  CSocket::OnReceive(nErrorCode);
}

void CDataSocket::OnClose(int nErrorCode) {
  if (m_pFile != NULL) {
&nbsp;   &nbsp;   delete m_pFile;
  &nbsp;   m_pFile = NULL;
  }
&nbsp;   if (m_pArchiveIn != NULL) {
&nbsp;   &nbsp;   m_pArchiveIn->Abort();
  &nbsp;   delete m_pArchiveIn;
  &nbsp;   m_pArchiveIn = NULL;
  }
&nbsp;   if (m_pArchiveOut != NULL) {
&nbsp;   &nbsp;   m_pArchiveOut->Abort();
  &nbsp;   delete m_pArchiveOut;
  &nbsp;   m_pArchiveOut = NULL;
  }
&nbsp;   CSocket::OnClose(nErrorCode);
}

// CData

class CData : public CObject {
public:
  CData();
  virtual ~CData();
  virtual void Serialize(CArchive &ar);

  CString m_strData; // Real data from here
};

void CData::Serialize(CArchive &ar) {
&nbsp;   if (ar.IsStoring()) {
&nbsp;   &nbsp;   ar << m_strData;
  }
&nbsp;   else {
&nbsp;   &nbsp;   ar >> m_strData;
  }
}

반응형

'Program > C & C++' 카테고리의 다른 글

MFC UI 꾸미기  (0) 2011.07.15
MFC를 이용한 범용 소켓을 이용한 예제  (0) 2011.07.13
COleDateTime Class  (0) 2011.07.13
Open CV  (0) 2011.04.11
c++콘솔 시계  (0) 2011.03.28