1、I 服务器:/ ServerDlg.cpp : implementation file/#include “stdafx.h“#include “Server.h“#include “ServerDlg.h“#ifdef _DEBUG#define new DEBUG_NEW#undef THIS_FILEstatic char THIS_FILE = _FILE_;#endif/ CAboutDlg dialog used for App Aboutclass CAboutDlg : public CDialogpublic:CAboutDlg();protected:DECLARE_MES
2、SAGE_MAP();CAboutDlg:CAboutDlg() : CDialog(CAboutDlg:IDD)void CAboutDlg:DoDataExchange(CDataExchange* pDX)CDialog:DoDataExchange(pDX);BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)END_MESSAGE_MAP()/ CServerDlg dialogCServerDlg:CServerDlg(CWnd* pParent /*=NULL*/): CDialog(CServerDlg:IDD, pParent)m_hIcon = Afx
3、GetApp()-LoadIcon(IDI_ICONAPP);void CServerDlg:DoDataExchange(CDataExchange* pDX)CDialog:DoDataExchange(pDX);DDX_Control(pDX, IDC_LIST_USER, m_lbUser);DDX_Text(pDX, IDC_EDIT_DISPLAY, m_strDisplay);BEGIN_MESSAGE_MAP(CServerDlg, CDialog)ON_WM_SYSCOMMAND()ON_WM_PAINT()ON_WM_QUERYDRAGICON()ON_BN_CLICKED
4、(IDC_BN_START, OnBnStart)ON_BN_CLICKED(IDC_BN_CLOSE, OnBnClose)ON_MESSAGE(WM_RECEIVE, OnReceive)ON_MESSAGE(WM_CLIENTCLOSE, OnClientClose)ON_MESSAGE(WM_ACCEPT, OnAccept)ON_WM_DESTROY()END_MESSAGE_MAP()/ CServerDlg message handlersBOOL CServerDlg:OnInitDialog()CDialog:OnInitDialog();ASSERT(IDM_ABOUTBO
5、X ASSERT(IDM_ABOUTBOX AppendMenu(MF_SEPARATOR);pSysMenu-AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);SetIcon(m_hIcon, TRUE); / Set big iconSetIcon(m_hIcon, FALSE); / Set small iconm_iNetPort = 3127;m_Server.Initialize(this);m_bServer = FALSE;GetDlgItem(IDC_BN_CLOSE)-EnableWindow(FALSE);return T
6、RUE; / return TRUE unless you set the focus to a controlvoid CServerDlg:OnSysCommand(UINT nID, LPARAM lParam)if (nID dlgAbout.DoModal();elseCDialog:OnSysCommand(nID, lParam);void CServerDlg:OnPaint() if (IsIconic()CPaintDC dc(this); / device context for paintingSendMessage(WM_ICONERASEBKGND, (WPARAM
7、) dc.GetSafeHdc(), 0);int cxIcon = GetSystemMetrics(SM_CXICON);int cyIcon = GetSystemMetrics(SM_CYICON);CRect rect;GetClientRect(int x = (rect.Width() - cxIcon + 1) / 2;int y = (rect.Height() - cyIcon + 1) / 2;dc.DrawIcon(x, y, m_hIcon);elseCDialog:OnPaint();HCURSOR CServerDlg:OnQueryDragIcon()retur
8、n (HCURSOR) m_hIcon;void CServerDlg:OnBnStart() / 创建套接字m_Server.Create(m_iNetPort);/ 开始监听m_Server.Listen();/ 显示CString strInfo;strInfo.LoadString(IDS_CREATE_SERVER);ShowInDisplay(strInfo);m_bServer = TRUE;GetDlgItem(IDC_BN_START)-EnableWindow(FALSE);GetDlgItem(IDC_BN_CLOSE)-EnableWindow(TRUE);void C
9、ServerDlg:OnBnClose() CloseServer();GetDlgItem(IDC_BN_START)-EnableWindow(TRUE);GetDlgItem(IDC_BN_CLOSE)-EnableWindow(FALSE);void CServerDlg:OnAccept()/ 创建新客户CMySocket *pNewClient = new CMySocket;pNewClient-Initialize(this);m_Server.Accept(*pNewClient);/ 放入链表中m_lsClient.AddTail(pNewClient);void CSer
10、verDlg:OnClientClose(WPARAM wParam, LPARAM lParam)CMySocket *p_delClient = (CMySocket*)wParam;/ 关闭该用户p_delClient-ShutDown();char bufferBUFFERSIZE;while(p_delClient-Receive(buffer, BUFFERSIZE)0);p_delClient-Close();/ 在用户链表中删除该用户POSITION psCur, psList = m_lsClient.GetHeadPosition();CMySocket *p_curCli
11、ent;while(psList!=NULL)psCur = psList;p_curClient = (CMySocket *)m_lsClient.GetNext(psList);if(p_delClient=p_curClient)m_lsClient.RemoveAt(psCur);break;/ 发送信息告诉其他用户该客户退出CString strMsg;strMsg.LoadString(IDS_CLIENT_CLOSE);NETMESSAGE netMessage(PTC_CLIENT_QUIT, p_delClient-GetName(), _T(“), p_delClient
12、-GetName() + strMsg);SendToAllClient(netMessage);/ 界面上清理该用户信息m_lbUser.DeleteString(m_lbUser.FindString(-1, p_delClient-GetName();ShowInDisplay(p_delClient-GetName() + strMsg);/ 删除该用户delete p_delClient;void CServerDlg:OnReceive(WPARAM wParam, LPARAM lParam)CMySocket *p_curClient = (CMySocket*)wParam;
13、NETMESSAGE netMessage;p_curClient-Receive(char *)switch(netMessage.type)case PTC_NEW: / 新客户加入NewClientAdd(p_curClient, break;case PTC_SAY: / 普通聊天ShowMessage(netMessage);break;/ 把加工过的信息发送给其他用户SendToAllClient(netMessage);void CServerDlg:CloseServer()if(!m_bServer) return;/ 向所有客户发送服务端关闭的信息CString strIn
14、fo;strInfo.LoadString(IDS_CLOSESERVER);NETMESSAGE netMessage(PTC_SYSTEM, _T(“), _T(“), strInfo);SendToAllClient(netMessage);/ 服务端界面显示关闭信息ShowInDisplay(strInfo);/ 关闭服务端m_Server.Close();/ 关闭客户端char bufferBUFFERSIZE;CMySocket *m_pClient;POSITION psList = m_lsClient.GetHeadPosition();while(psList!=NULL)
15、m_pClient = (CMySocket *)m_lsClient.GetNext(psList);m_pClient-ShutDown();while(m_pClient-Receive(buffer, BUFFERSIZE)0);m_pClient-Close();delete m_pClient;m_lsClient.RemoveAll();m_bServer = FALSE;/ 向所有户发出信息void CServerDlg:SendToAllClient(const NETMESSAGE POSITION psList = m_lsClient.GetHeadPosition()
16、;while(psList!=NULL)m_pClient = (CMySocket *)m_lsClient.GetNext(psList);m_pClient-SendMsg(netMessage);void CServerDlg:ShowInDisplay(CString str)m_strDisplay += str + “rn“;UpdateData(false);void CServerDlg:OnDestroy() CDialog:OnDestroy();/ TODO: Add your message handler code here/ 新用户加入 void CServerD
17、lg:NewClientAdd(CMySocket *p_client, NETMESSAGE *netMessage)/ 存入用户名字p_client-SetName(netMessage-form);/ 在列表框中显示该用户m_lbUser.AddString(p_client-GetName();/ 发送用户列表给该客户NETMESSAGE netMsg(PTC_USER_LIST, _T(“), _T(“), _T(“);int iListLen = m_lbUser.GetCount();CString strMsg;for(int index=m_lbUser.GetTopInde
18、x(); indexSendMsg(netMsg);/ 加工信息strMsg.LoadString(IDS_NEW_CLIENT);strMsg = p_client-GetName() + strMsg;strcpy(netMessage-data, (LPCTSTR)strMsg);/ 显示该用户进入ShowInDisplay(strMsg);/ 显示普通消息void CServerDlg:ShowMessage(NETMESSAGE netMessage)CString strTo = netMessage.to;if(strTo=_T(“)strTo = “所有人“;CString s
19、trForm = netMessage.form;CString strMsg = netMessage.data;CString strOut = strForm + “对“ + strTo + “说:“ + strMsg;ShowInDisplay(strOut);II 客户端:/ ClientDlg.cpp : implementation file/#include “stdafx.h“#include “Client.h“#include “ClientDlg.h“#ifdef _DEBUG#define new DEBUG_NEW#undef THIS_FILEstatic cha
20、r THIS_FILE = _FILE_;#endif/ CAboutDlg dialog used for App Aboutclass CAboutDlg : public CDialogpublic:CAboutDlg();enum IDD = IDD_ABOUTBOX ;protected:virtual void DoDataExchange(CDataExchange* pDX); / DDX/DDV supportprotected:DECLARE_MESSAGE_MAP();CAboutDlg:CAboutDlg() : CDialog(CAboutDlg:IDD)void C
21、AboutDlg:DoDataExchange(CDataExchange* pDX)CDialog:DoDataExchange(pDX);BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)END_MESSAGE_MAP()/ CClientDlg dialogCClientDlg:CClientDlg(CWnd* pParent /*=NULL*/): CDialog(CClientDlg:IDD, pParent)m_strDisplay = _T(“);m_strSend = _T(“);m_bWhispering = FALSE;m_hIcon = AfxGe
22、tApp()-LoadIcon(IDR_MAINFRAME);void CClientDlg:DoDataExchange(CDataExchange* pDX)CDialog:DoDataExchange(pDX);DDX_Control(pDX, IDC_LIST_USER, m_lbUser);DDX_Text(pDX, IDC_EDIT_DIAPLAY, m_strDisplay);DDX_Text(pDX, IDC_EDIT_SEND, m_strSend);DDX_Check(pDX, IDC_CHECK_WHISPERING, m_bWhispering);BEGIN_MESSA
23、GE_MAP(CClientDlg, CDialog)ON_WM_SYSCOMMAND()ON_WM_PAINT()ON_WM_QUERYDRAGICON()ON_BN_CLICKED(IDC_BN_CONNECT, OnBnConnect)ON_BN_CLICKED(IDC_BN_CLOSE, OnBnClose)ON_BN_CLICKED(IDC_BN_SEND, OnBnSend)ON_MESSAGE(WM_RECEIVE, OnReceive)ON_MESSAGE(WM_SOCKETCLOSE, OnServerClose)ON_MESSAGE(WM_SEND, OnSend)ON_M
24、ESSAGE(WM_CONNCET, OnConnect)ON_LBN_DBLCLK(IDC_LIST_USER, OnDblclkListUser)END_MESSAGE_MAP()/ CClientDlg message handlersBOOL CClientDlg:OnInitDialog()CDialog:OnInitDialog();ASSERT(IDM_ABOUTBOX ASSERT(IDM_ABOUTBOX AppendMenu(MF_SEPARATOR);pSysMenu-AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);Se
25、tIcon(m_hIcon, TRUE); / Set big iconSetIcon(m_hIcon, FALSE); / Set small icon/ 参数初始化m_Socket.Initialize(this);m_strNetIP = _T(“127.0.0.1“);m_iNetPort = 3127;m_bConnect = FALSE;GetDlgItem(IDC_BN_CLOSE)-EnableWindow(FALSE);GetDlgItem(IDC_BN_SEND)-EnableWindow(FALSE);return TRUE; / return TRUE unless y
26、ou set the focus to a controlvoid CClientDlg:OnSysCommand(UINT nID, LPARAM lParam)if (nID dlgAbout.DoModal();elseCDialog:OnSysCommand(nID, lParam);void CClientDlg:OnPaint() if (IsIconic()CPaintDC dc(this); / device context for paintingSendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);int c
27、xIcon = GetSystemMetrics(SM_CXICON);int cyIcon = GetSystemMetrics(SM_CYICON);CRect rect;GetClientRect(int x = (rect.Width() - cxIcon + 1) / 2;int y = (rect.Height() - cyIcon + 1) / 2;dc.DrawIcon(x, y, m_hIcon);elseCDialog:OnPaint();HCURSOR CClientDlg:OnQueryDragIcon()return (HCURSOR) m_hIcon;void CC
28、lientDlg:OnBnConnect() CString strConnectError;/ 获取用户名字CInputDlg inputDlg;int iResult = inputDlg.DoModal();if(iResult=IDCANCEL)return;m_strName = inputDlg.m_strName;/ 创建套接字if(!m_Socket.Create()strConnectError.LoadString(IDS_FAIL_CREATE_SOCKET);ShowInDisplay(strConnectError);return;CString strInfo;st
29、rInfo.LoadString(IDS_CONNECTING);ShowInDisplay(strInfo);/ 连接服务器if(!m_Socket.Connect(m_strNetIP, m_iNetPort)int n = m_Socket.GetLastError();strConnectError.LoadString(IDS_FAIL_CONNECT);ShowInDisplay(strConnectError);return;strInfo.LoadString(IDS_SUCCEED_CONNECT);ShowInDisplay(strInfo);m_bConnect = TR
30、UE;/ 发送自已的名字NETMESSAGE netMessage(PTC_NEW, m_strName, _T(“), _T(“);m_Socket.SendMsg(netMessage);GetDlgItem(IDC_BN_CONNECT)-EnableWindow(FALSE);GetDlgItem(IDC_BN_CLOSE)-EnableWindow(TRUE);GetDlgItem(IDC_BN_SEND)-EnableWindow(TRUE);void CClientDlg:OnBnClose() if(m_bConnect) m_Socket.Close();m_bConnect
31、 = FALSE;GetDlgItem(IDC_BN_CONNECT)-EnableWindow(TRUE);GetDlgItem(IDC_BN_CLOSE)-EnableWindow(FALSE);GetDlgItem(IDC_BN_SEND)-EnableWindow(FALSE);m_lbUser.ResetContent();CString strMsg;strMsg.LoadString(IDS_BREAK);ShowInDisplay(strMsg);void CClientDlg:OnBnSend() OnSend();m_strSend = _T(“);UpdateData(F
32、ALSE);void CClientDlg:OnReceive()NETMESSAGE netMessage;m_Socket.Receive(char *)CString strForm = netMessage.form;/ 过滤自已发出的信息if(strForm=m_strName) return;CString strTo = netMessage.to;CString strMsg = netMessage.data;switch(netMessage.type)case PTC_USER_LIST: / 用户列表m_lbUser.AddString(strMsg);break;ca
33、se PTC_NEW: / 新用户进入m_lbUser.AddString(strForm);ShowInDisplay(strMsg);break;case PTC_SAY:ShowMessage(netMessage);case PTC_WHISPERING: / 密语if(strTo!=m_strName) return;ShowMessage(netMessage);break;case PTC_CLIENT_QUIT: / 有用户退出m_lbUser.DeleteString(m_lbUser.FindString(-1, strForm);ShowInDisplay(strMsg)
34、;break;void CClientDlg:OnServerClose()if(!m_bConnect) return;CString strMsg;strMsg.LoadString(IDS_SERVER_CLOSE);ShowInDisplay(strMsg);m_Socket.Close();m_bConnect = FALSE;GetDlgItem(IDC_BN_CONNECT)-EnableWindow(TRUE);GetDlgItem(IDC_BN_CLOSE)-EnableWindow(FALSE);GetDlgItem(IDC_BN_SEND)-EnableWindow(FA
35、LSE);m_lbUser.ResetContent();void CClientDlg:OnSend()UpdateData(TRUE);/ 主要是填充 NETMESSAGE 结构体NETMESSAGE netMessage;strcpy(netMessage.form, m_strName);strcpy(netMessage.data, m_strSend);/ 取得列表框中的用户if(m_lbUser.GetText(m_lbUser.GetCurSel(), netMessage.to)=LB_ERR)strcpy(netMessage.to, _T(“);if(m_bWhisper
36、ing)/ 密语CString strTo = netMessage.to;if(strTo=_T(“) MessageBox(“请选择对方!“, “错误“);return;netMessage.type = PTC_WHISPERING;elsestrcpy(netMessage.to, _T(“所有人“);netMessage.type = PTC_SAY;/ 发送该信息m_Socket.SendMsg(netMessage);/ 显示发送信息CString strTo = netMessage.to;CString strMsg = netMessage.data;ShowInDispl
37、ay(“你对“ + strTo + “说:“ + strMsg);void CClientDlg:ShowInDisplay(CString str)m_strDisplay += str + “rn“;UpdateData(FALSE);void CClientDlg:ShowMessage(const NETMESSAGE if(strTo=_T(“)strTo = “所有人“;else if(strTo=m_strName)strTo = “你“;CString strForm = netMessage.form;CString strMsg = netMessage.data;CString strOut = strForm + “对“ + strTo + “说:“ + strMsg;ShowInDisplay(strOut);void CClientDlg:OnDblclkListUser() / TODO: Add your control notification handler code herem_lbUser.SetCurSel(-1);void CClientDlg:OnConnect()m_bConnect = TRUE;