📄 datasocket.cpp
字号:
// DataSocket.cpp : implementation file
//
#include "stdafx.h"
#include "ChatCSocket.h"
#include "DataSocket.h"
#include "CMessg.h"
#include "ChatCSocketDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CDataSocket
CDataSocket::CDataSocket()
{
m_aSessionIn=NULL;
m_aSessionOut=NULL;
m_sfSocketFile=NULL;
}
CDataSocket::~CDataSocket()
{
if(m_aSessionIn)
delete m_aSessionIn;
if(m_aSessionOut)
delete m_aSessionOut;
if(m_sfSocketFile)
delete m_sfSocketFile;
}
// Do not edit the following lines, which are needed by ClassWizard.
#if 0
BEGIN_MESSAGE_MAP(CDataSocket, CSocket)
//{{AFX_MSG_MAP(CDataSocket)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
#endif // 0
/////////////////////////////////////////////////////////////////////////////
// CDataSocket member functions
void CDataSocket::OnClose(int nErrorCode)
{
// TODO: Add your specialized code here and/or call the base class
m_pDlg->OnSocketClose(this);
return;
CSocket::OnClose(nErrorCode);
}
void CDataSocket::OnReceive(int nErrorCode)
{
// TODO: Add your specialized code here and/or call the base class
static CMessg msg;
CString buffer;
do
{
TRY
{
msg.Serialize(*m_aSessionIn);
buffer+=msg.m_strText;
}
CATCH (CFileException, e)
{
m_pDlg->OnSocketClose(this);
}
END_CATCH
}while(!m_aSessionIn->IsBufferEmpty());
msg.m_strText=buffer;
m_pDlg->OnSocketReceive(this, msg);
}
void CDataSocket::CloseSocket()
{
if(m_aSessionIn)
{
delete m_aSessionIn;
m_aSessionIn=NULL;
}
if(m_aSessionOut)
{
delete m_aSessionOut;
m_aSessionOut=NULL;
}
if(m_sfSocketFile)
{
delete m_sfSocketFile;
m_sfSocketFile=NULL;
}
Close();
}
void CDataSocket::Init(CChatCSocketDlg * pDlg)
{
m_sfSocketFile= new CSocketFile(this);
m_aSessionIn=new CArchive(m_sfSocketFile,CArchive::load);
m_aSessionOut=new CArchive(m_sfSocketFile,CArchive::store);
m_pDlg=pDlg;
}
BOOL CDataSocket::SendMessage(CMessg& msg)
{
if (m_aSessionOut != NULL)
{
msg.Serialize(*m_aSessionOut);
m_aSessionOut->Flush();
return TRUE;
}
else
return FALSE;
}
CString CDataSocket::GetLocalHostName() //获得本地计算机名称
{
char szHostName[256];
if(gethostname(szHostName,sizeof(szHostName))!=0)
return CString("");
else
return CString(szHostName);
}
CString CDataSocket::GetIPAddress()//获得本地IP
{
hostent* lpHostEnt;
char szHostName[256];
LPSTR lpAddr;
struct in_addr inAddr;
if(gethostname(szHostName,sizeof(szHostName))!=0)
return CString("");
lpHostEnt=gethostbyname(szHostName);
if(lpHostEnt==NULL)
return CString("");
//获取IP列表,这里我们只关心其中第一个IP地址
lpAddr=lpHostEnt->h_addr_list[0];
if(lpAddr==NULL)
return CString("");
memmove(&inAddr,lpAddr,4);
return CString(inet_ntoa(inAddr));
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -