資源簡介
在VS2012下用MFC寫成的簡易網絡聊天室程序,包含的知識點有ODBC連接MySql數據庫、CSocket類的運用等,對于mfc新手是個不錯的學習資源(如果項目無法在VS2012下運行,有可能是因為VS版本不匹配(由于之前是先用VS2013寫的再轉到VS2012),請對著項目右鍵,然后點屬性,找到配置屬性,將常規中的平臺工具集選擇為Visual Studio 2012 (v110),應用即可)
代碼片段和文件信息
#include?“stdafx.h“
#include?“ClientSocket.h“
CClientSocket::CClientSocket()
{
}
CClientSocket::~CClientSocket()
{
}
//接收服務器消息的回調函數
void?CClientSocket::OnReceive(int?nErrorCode)
{
//?TODO:??在此添加專用代碼和/或調用基類
char*?pData?=?NULL;
pData?=?new?char[1024];
memset(pData?0?sizeof(char)*?1024);
UCHAR?leng?=?0;
CString?str;
leng?=?Receive(pData?1024?0);
str?=?pData;
//如果服務器通知更新聊天室列表
if?(-1?!=?strUpdate(str))
{
((ClineClientDlg?*)theApp.GetMainWnd())->UpdateUsers(str?strUpdate(str));
}
//否則就更新聊天窗口內容
else
{
//更新數據庫中的聊天記錄
try
{
((ClineClientDlg?*)theApp.GetMainWnd())->updateDatabase(str);
}
catch(CException*?e?)
{
e->ReportError();
//delete(e);
}
CString?strOld;
((ClineClientDlg?*)theApp.GetMainWnd())->GetDlgItemText(IDC_EDIT_RECIEVEMSG?strOld);
str?=?strOld?+?“\r\n“?+?str;
//?在編輯框中顯示接收到的數據
((ClineClientDlg?*)theApp.GetMainWnd())->SetDlgItemTextW(IDC_EDIT_RECIEVEMSG?str);
}
delete?pData;
pData?=?NULL;
CSocket::OnReceive(nErrorCode);
}
//向服務器發送消息
bool?CClientSocket::SendMSG(LPSTR?lpBuff?int?nlen)
{
//生成協議頭
if?(Send(lpBuff?nlen)?==?SOCKET_ERROR)
{
AfxMessageBox(_T(“發送錯誤!“));
return?FALSE;
}
return??TRUE;
}
int?CClientSocket::strUpdate(CString?str)
{
return?str.Find(_T(“MUPDATEUSERLIST“));
}
評論
共有 條評論