按键盘上方向键 ← 或 → 可快速上下翻页,按键盘上的 Enter 键可回到本书目录页,按键盘上方向键 ↑ 可回到本页顶部!
————未阅读完?加入书签已便下次继续阅读!
}
接着为“连接”菜单项编写响应函数,代码如下:
void CChatClientDoc::OnConnect()
{
// TODO: Add your mand handler code here
CLogDlg dlg;
if(dlg。DoModal() == IDOK)
{
if(ConnectSocket(dlg。m_Name; dlg。m_Server; dlg。m_Port))
bIsConnected = TRUE;
else
AfxMessageBox(〃连接服务器失败!〃);
}
}
当连接后,应该使“连接”菜单项无效,为消息 UPDATA_MAND_UI 添加响应函
数如下:
void CChatClientDoc::OnUpdateConnect(CCmdUI* pCmdUI)
{
// TODO: Add your mand update UI handler code here
pCmdUI…》Enable(!bIsConnected);
}
·315 ·
…………………………………………………………Page 327……………………………………………………………
Visual C++ 6。0 程序设计从入门到精通
为“断开”菜单项添加响应函数,代码如下:
void CChatClientDoc::OnDisconnect()
{
// TODO: Add your mand handler code here
DeleteContents();
bIsConnected = FALSE;
}
当断开后,应当使“断开”菜单项无效,为消息 UPDATA_MAND_UI 添加如下响
应函数:
void CChatClientDoc::OnUpdateDisconnect(CCmdUI* pCmdUI)
{
// TODO: Add your mand update UI handler code here
pCmdUI…》Enable(bIsConnected);
}
为 ConnectSocket()函数编写如下代码:
BOOL CChatClientDoc::ConnectSocket(LPCTSTR lpszHandle; LPCTSTR lpszAddress; int nPort)
{
m_strName = lpszHandle;
m_pSocket = new CChatSocket(this);
//创建 socket 失败
if (!m_pSocket…》Create())
{
delete m_pSocket;
m_pSocket = NULL;
AfxMessageBox(〃创建 socket 失败!〃);
return FALSE;
}
//连接失败
if(!m_pSocket…》Connect(lpszAddress; nPort))
{
delete m_pSocket;
m_pSocket = NULL;
return FALSE;
}
m_pFile = new CSocketFile(m_pSocket);
//用于数据接收和发送
m_pArchiveIn = new CArchive(m_pFile;CArchive::load);
m_pArchiveOut = new CArchive(m_pFile;CArchive::store);
//将用户名发送给服务器
SendMsg(m_strName; SENDING_NICKNAME; false);
·316 ·
…………………………………………………………Page 328……………………………………………………………
第 11 章 网络编程
CString strTemp;
strTemp。Format(〃进入聊天室〃);
//作为普通消息发送给服务器
SendMsg(strTemp; NORMAL_MESSAGE; true);
return TRUE;
}
为 SendMsg()函数编写如下代码:
void CChatClientDoc::SendMsg(CString& strText; int mCode; BOOL bSendHandle)
{
if (m_pArchiveOut != NULL)
{
CMsg msg;
msg。code = mCode;
msg。m_strText = (bSendHandle ? m_strName + _T(〃: 〃) + strText : strText);
TRY
{
msg。Serialize(*m_pArchiveOut);
m_pArchiveOut…》Flush();
}
CATCH(CFileException; e)
{
m_pArchiveOut…》Abort();
delete m_pArchiveOut;
m_pArchiveOut = NULL;
CString strTemp;
strTemp。Format(〃发送失败〃);
DisplayMsg(strTemp);
}
END_CATCH
}
}
为 ProcessReceive() 函数编写如下代码:
void CChatClientDoc::ProcessReceive()
{
do
{
ReceiveMsg();
if (m_pSocket == NULL)
return;
·317 ·
…………………………………………………………Page 329……………………………………………………………
Visual C++ 6。0 程序设计从入门到精通
}
while(!m_pArchiveIn…》IsBufferEmpty());
}
为 ReceiveMsg() 函数编写如下代码:
void CChatClientDoc::ReceiveMsg()
{
CMsg msg;
TRY
{
msg。Serialize(*m_pArchiveIn);
if(msg。code == SENDING_CHATTERS_LIST)
{
//更新用户列表
UpdateChattersList(&msg);
return;
}
if(msg。code == USED_NAME)
{
//如果是用户名已存在信息则关闭连接,退出
AfxMessageBox(msg。m_strText);
msg。m_bClose = TRUE;
OnDisconnect();
return;
}
//显示消息
DisplayMsg(msg。m_strText);
}
CATCH(CFileException; e)
{