⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 chatclientdlg.cpp

📁 c++ 图表的设计
💻 CPP
字号:
// ChatClientDlg.cpp : implementation file
//

#include "stdafx.h"
#include "ChatClient.h"
#include "ChatClientDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
		// No message handlers
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CChatClientDlg dialog

CChatClientDlg::CChatClientDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CChatClientDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CChatClientDlg)
		// NOTE: the ClassWizard will add member initialization here
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);

	m_svr=INVALID_SOCKET;
	m_bConnected=FALSE;
}

void CChatClientDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CChatClientDlg)
	DDX_Control(pDX, IDC_MSG, m_editMsg);
	DDX_Control(pDX, IDC_NAME, m_editName);
	DDX_Control(pDX, IDC_LIST_USER, m_listUser);
	DDX_Control(pDX, IDC_LIST_MSG, m_listMessage);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CChatClientDlg, CDialog)
	//{{AFX_MSG_MAP(CChatClientDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(ID_CONN_SVR, OnConnSvr)
	ON_BN_CLICKED(IDC_SEND, OnSend)
	ON_NOTIFY(NM_CLICK, IDC_LIST_USER, OnClickListUser)
	ON_MESSAGE(WM_MSG_DATA,OnSocketData)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CChatClientDlg message handlers

BOOL CChatClientDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	// TODO: Add extra initialization here
	InitCtls();
	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CChatClientDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CChatClientDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CChatClientDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

void CChatClientDlg::OnConnSvr() 
{
	
	// TODO: Add your control notification handler code here
	if(m_bConnected)
		return;

	int nLen=m_editName.GetWindowTextLength();
	if(nLen<1 || nLen>8)
	{
		AfxMessageBox(_T("连接服务器失败:用户名太长或者太短!"));
		return;
	}

	if(m_svr==INVALID_SOCKET)
	{
		m_svr=::socket(AF_INET,SOCK_DGRAM,0);
		if(m_svr==INVALID_SOCKET)
		{
			AfxMessageBox(_T("连接服务器失败:")+this->GetLastErrorMsg());
		}
	

		memset(&m_svrAddr,0,sizeof(SOCKADDR_IN));
		m_svrAddr.sin_family=AF_INET;
		m_svrAddr.sin_addr.s_addr=inet_addr("127.0.0.1");
		m_svrAddr.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");
		m_svrAddr.sin_port=htons(16000);


		::WSAAsyncSelect(m_svr,this->GetSafeHwnd(),WM_MSG_DATA,FD_READ);
	}
	
	char data[10];
	memset(data,0,10);
	data[0]=EM_REG_ID;
	m_editName.GetWindowText(data+1,9);
	
	int ir=::sendto(m_svr,data,10,0,(sockaddr*)&m_svrAddr,sizeof(SOCKADDR_IN));
	if(ir==SOCKET_ERROR)
	{
		AfxMessageBox(_T("发送注册信息失败:")+this->GetLastErrorMsg());
	}
	else
	{
		m_editName.GetWindowText(localname);
	}
}

void CChatClientDlg::OnRegData(char* pData)
{
#define REG_OK 0
#define REG_FAILED 1
	if (pData)
	{
		if(*pData==REG_OK)
		{
			AfxMessageBox(_T("已经成功注册ID!刷新用户中......"));
			char data[1];
			data[0]=EM_USERS;
			int ir=::sendto(m_svr,data,1,0,(sockaddr*)&m_svrAddr,sizeof(SOCKADDR_IN));
			if(ir==SOCKET_ERROR)
			{
				AfxMessageBox(_T("发送获取用户列表失败:")+this->GetLastErrorMsg());
			}

			m_bConnected=TRUE;
		}
		else
		{
			if(!m_bConnected)
				AfxMessageBox(_T("注册ID失败,该ID已被使用!"));
		}
	}
}

void CChatClientDlg::OnMsgData(char* pData)
{
	char from[9],to[9];

	memset(from,0,9);
	memset(to,0,9);

	memcpy(from,pData,8);
	memcpy(to,pData+8,8);
	CString strMsg;
	strMsg.Format(_T("%s"),pData+8+8);

	AddMsg(from,_T("我"),strMsg);
}

void CChatClientDlg::AddMsg(CString from,CString to,CString msg)
{
	int nCount=m_listMessage.GetItemCount();
	int index=m_listMessage.InsertItem(nCount,from);
	m_listMessage.SetItemText(index,1,to);
	m_listMessage.SetItemText(index,2,msg);
}


void CChatClientDlg::OnMsgToAll(char* pData)
{
	if(pData)
	{		
		CString strMsg;
		strMsg.Format(_T("系统广播:%s"),pData);
		AfxMessageBox(strMsg);
	}
}

void CChatClientDlg::OnUserListData(char* pData,int nCount)
{
	LVFINDINFO info;
	info.flags = LVFI_PARTIAL|LVFI_STRING;

	for (int i=0;i<nCount;i++)
	{
		char name[9];
		memcpy(name,pData+i*8,8);
		name[8]='\0';
		
		info.psz = name;
		if(m_listUser.FindItem(&info)==-1)
		{
			m_listUser.InsertItem(0,name);
		}		
	}	
}

LRESULT CChatClientDlg::OnSocketData(WPARAM,LPARAM)
{
	char data[1024];
	memset(data,0,1024);
	SOCKADDR_IN addr;
	int size=sizeof(SOCKADDR_IN);
	int ir=::recvfrom(m_svr,data,1024,0,(sockaddr*)&addr,&size);
	if(ir==SOCKET_ERROR || ir==0)
		return 0;
	else
	{
		char* pData=data+1;
		switch(data[0])
		{
		case EM_MSG:
			OnMsgData(pData);
			break;
		case EM_REG_ID:
			OnRegData(pData);
			break;
		case EM_USERS:
			OnUserListData(pData+1,pData[0]);
			break;
		case EM_ALL_MSG:
			OnMsgToAll(pData);
			break;
		case EM_USERS_EXIT:
			OnUserExit(pData);
			break;
		default:;
		}
	}
	
	return 0;
}

void CChatClientDlg::OnUserExit(char* pData)
{
	if(pData)
	{
		LVFINDINFO info;
		info.flags = LVFI_PARTIAL|LVFI_STRING;
		
		
		info.psz = pData;
		int index=m_listUser.FindItem(&info);
		if(index!=-1)
		{
			m_listUser.DeleteItem(index);
		}

		if (strTo==pData)
		{
			strTo=_T("");
		}
	}
}

void CChatClientDlg::CloseSocket()
{
	if(m_svr!=INVALID_SOCKET)
		::closesocket(m_svr);
}

CString CChatClientDlg::GetLastErrorMsg()
{
	int ir=::WSAGetLastError();
	CString errMsg;
	errMsg.Format(_T("错误信息:%d"),ir);
	return errMsg;
}

void CChatClientDlg::InitCtls()
{
	m_listUser.DeleteAllItems();
	m_listUser.InsertColumn(0,_T("用户"),LVCFMT_LEFT,100);

	m_listMessage.DeleteAllItems();
	m_listMessage.InsertColumn(0,_T("From"),LVCFMT_LEFT,100);
	m_listMessage.InsertColumn(1,_T("To"),LVCFMT_LEFT,100);

	CRect rc;
	m_listMessage.GetClientRect(rc);
	m_listMessage.InsertColumn(2,_T("Message"),LVCFMT_LEFT,rc.Width()-200);

	m_listMessage.SetExtendedStyle(LVS_EX_HEADERDRAGDROP|LVS_EX_GRIDLINES|LVS_EX_FULLROWSELECT);
}

void CChatClientDlg::OnCancel() 
{
	// TODO: Add extra cleanup here
	if(m_svr!=INVALID_SOCKET)
	{	
		char data[9];
		memset(data,0,9);
		data[0]=EM_DEL_ID;
		strcpy(data+1,localname);
		::sendto(m_svr,data,9,0,(sockaddr*)&m_svrAddr,sizeof(SOCKADDR_IN));

		CloseSocket();
	}	

	CDialog::OnCancel();
}

void CChatClientDlg::OnSend() 
{
	if(!m_bConnected)
	{
		AfxMessageBox(_T("尚未注册ID!"));
		return;
	}

	CString msg;
	char data[128];

	m_editMsg.GetWindowText(msg);
	int nLen=msg.GetLength();
	if(nLen<0 ||nLen>64)
	{
		AfxMessageBox(_T("消息太长或者太短!"));
	}
	else if (strTo.GetLength()<1)
	{
		AfxMessageBox(_T("消目标不存在或者已离线!"));
	}
	else
	{
		memset(data,0,128);
		data[0]=EM_MSG;
		strncpy(data+1,localname,8);
		strncpy(data+8+1,strTo,8);
		strncpy(data+16+1,msg,nLen);

		int ir=::sendto(m_svr,data,128,0,(sockaddr*)&m_svrAddr,sizeof(SOCKADDR_IN));
		if(ir==SOCKET_ERROR)
		{
			AfxMessageBox(_T("发送信息失败:")+this->GetLastErrorMsg());
		}
		else
		{
			AddMsg(_T("我"),strTo,msg);
		}
	}	
}

void CChatClientDlg::OnClickListUser(NMHDR* pNMHDR, LRESULT* pResult) 
{
	// TODO: Add your control notification handler code here
	int index=m_listUser.GetSelectionMark();
	if(index!=-1)
	{
		strTo=m_listUser.GetItemText(index,0);
	}

	this->GetDlgItem(IDC_SEND_TO)->SetWindowText(_T("发送至:")+strTo);

	*pResult = 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -