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

📄 serverdlg.cpp

📁 基于UDP协议的winsock聊天室
💻 CPP
字号:
// ServerDlg.cpp : implementation file
//

#include "stdafx.h"
#include "Server.h"
#include "ServerDlg.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()

/////////////////////////////////////////////////////////////////////////////
// CServerDlg dialog

CServerDlg::CServerDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CServerDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CServerDlg)
	m_MemCounts = 0;
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CServerDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CServerDlg)
	DDX_Text(pDX, IDC_EDIT_MemCount, m_MemCounts);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CServerDlg, CDialog)
	//{{AFX_MSG_MAP(CServerDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BROWSE, OnBrowse)
	ON_BN_CLICKED(IDC_SENDFILE, OnSendfile)
	ON_LBN_SELCHANGE(IDC_MEMBERLIST, OnSelchangeMemberlist)
	ON_BN_CLICKED(IDC_SENDMESSAGE, OnSendmessage)
	ON_BN_CLICKED(IDC_KICK, OnKick)
	ON_BN_CLICKED(IDC_BUTTON_Saverecord, OnBUTTONSaverecord)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CServerDlg message handlers


UINT ThreadProc(LPVOID par)
{
	CServerDlg *pServerDlg = (CServerDlg *)par;
	return 0;
}

BOOL CServerDlg::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

	if(m_ListenSocket.Create(5216))
	{
		m_ListenSocket.Listen();

		SetDlgItemText(IDC_MESSAGEDISP, "服务器正常启动!");
		CListBox *pListBox = (CListBox *)GetDlgItem(IDC_MEMBERLIST);
		pListBox->AddString("所有人");
		pListBox->SetCurSel(0);
		OnSelchangeMemberlist();

		m_DataSocket.Create(0, SOCK_DGRAM);

		m_nClient = 0;
	}
	else
	{
		MessageBox("服务器已经运行!");
		EndDialog(IDCANCEL);
	}
	
	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CServerDlg::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 CServerDlg::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 CServerDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

void CServerDlg::OnAccept()
{
	CString str, str1;
	UINT port;
	CClientSocket *m_pClientSocket;
	m_pClientSocket = new CClientSocket();
	m_ListenSocket.Accept(*m_pClientSocket);
	m_ClientList.AddTail(m_pClientSocket);
	m_pClientSocket->GetPeerName(str, port);
	str1.Format("%d", port);
	str += ":" +str1;
	CRichEditCtrl *pRichEdit = (CRichEditCtrl *)GetDlgItem(IDC_MESSAGEDISP);
	pRichEdit->GetWindowText(str1);
	str1 += "\r\n欢迎来自" + str + "的朋友!";
	pRichEdit->SetWindowText(str1);
	m_MemCounts=m_ClientList.GetCount();

	CRichEditCtrl *pRich = ((CRichEditCtrl *)GetDlgItem(IDC_MESSAGEDISP));
	
	if(pRich->GetLineCount() > 14)
	{
		pRich->LineScroll(1, 0);
		pRich->LineScroll(1, 0);
	}
	UpdateData(FALSE);

/*	m_ListenSocket.Accept(m_tempAcceptSocket);
	m_tempAcceptSocket.GetPeerName(str, port);*/
}

void CServerDlg::OnClose(CClientSocket *pDelSocket)
{
	int i = 0;
	CClientSocket *pClientSocket;
	CString str, str1;
	UINT port;
	pDelSocket->GetPeerName(str, port);
	CListBox *pListBox = (CListBox *)GetDlgItem(IDC_MEMBERLIST);
	str1.Format("%d", port);
	str += ":" +str1;

	CRichEditCtrl *pRichEdit = (CRichEditCtrl *)GetDlgItem(IDC_MESSAGEDISP);
	pRichEdit->GetWindowText(str1);
	str1 += "\r\n来自" + str + "的朋友离开了聊天室!";
	pRichEdit->SetWindowText(str1);

	m_MemCounts=m_ClientList.GetCount()-1;
//	pListBox->DeleteString(pListBox->FindString(0, str));
	

//	if(pListBox->FindString(-1, pDelSocket->m_strNickname) != LB_ERR)
	if(m_ClientList.GetCount()>0)
	{
		for(i=0; i<m_ClientList.GetCount(); i++)
		{
			pClientSocket = m_ClientList.GetAt(m_ClientList.FindIndex(i));
			if(pDelSocket != pClientSocket)
			{
				str.Format("%d", pDelSocket->m_nUDPPort);
				str = "Del" + pDelSocket->m_strPeerAddress + "/" + str + "/" + pDelSocket->m_strNickname;
				pClientSocket->Send(str, str.GetLength());
				Sleep(100);
			}
			else
			{
				m_ClientList.RemoveAt(m_ClientList.FindIndex(i));
			}			
		}
	}

/*	for(i=0; i<m_ClientList.GetCount(); i++)
	{
		pClientSocket = m_ClientList.GetAt(m_ClientList.FindIndex(i));
		if(pDelSocket == pClientSocket)
		{
			m_ClientList.RemoveAt(m_ClientList.FindIndex(i));
			break;
		}
	}
*/
	CRichEditCtrl *pRich = ((CRichEditCtrl *)GetDlgItem(IDC_MESSAGEDISP));
	
	if(pRich->GetLineCount() > 14)
	{
		pRich->LineScroll(1, 0);
		pRich->LineScroll(1, 0);
	}
	pDelSocket->Close();
	UpdateData(FALSE);

/*	m_tempAcceptSocket.GetPeerName(str, port);
	

	m_tempAcceptSocket.Close();	*/
}

void CServerDlg::OnBrowse() 
{
	// TODO: Add your control notification handler code here
	CString str;
	CFileDialog OpenDlg(true);
	if(OpenDlg.DoModal() == IDOK)
	{
		SetDlgItemText(IDC_FILEPATH, OpenDlg.m_ofn.lpstrFile);
	}
}

void CServerDlg::OnSendfile() 
{
	// TODO: Add your control notification handler code here
	SetDlgItemText(IDC_FILEPATH, "");
}

void CServerDlg::OnSelchangeMemberlist() 
{
	// TODO: Add your control notification handler code here
	CString str;
	CListBox *pListBox = (CListBox *)GetDlgItem(IDC_MEMBERLIST);
	pListBox->GetText(pListBox->GetCurSel(), str);;
	CEdit *pEdit = (CEdit *)GetDlgItem(IDC_MEMBERSELECT);
	pEdit->SetWindowText(str);
}

void CServerDlg::OnSendmessage() 
{
	// TODO: Add your control notification handler code here
	int i = 0;
	UINT nPeerPort = 0;
	CString Message, MsgTo, PeerAddress, TempMessage;
	CClientSocket *m_pClientSocket;
	CButton *pButton = (CButton *)GetDlgItem(IDC_CHECK1);
	GetDlgItemText(IDC_MESSAGEINPUT, Message);
	
	if(Message.GetLength() == 0)	//输入消息框为空
	{
		MessageBox("不能发送空信息!");
	}
	else							//输入消息框不为空
	{
		GetDlgItemText(IDC_MEMBERSELECT, MsgTo);
		if(pButton->GetCheck())		//私聊
		{
			if(MsgTo.Compare("所有人") == 0)	//对所有人
			{
				for(i=0; i<m_ClientList.GetCount(); i++)
				{
					GetDlgItemText(IDC_MESSAGEINPUT, Message);
					m_pClientSocket = m_ClientList.GetAt(m_ClientList.FindIndex(i));
					Message = "管理员 悄悄地 对你说: " + Message;
					nPeerPort = m_pClientSocket->m_nUDPPort;
					PeerAddress = m_pClientSocket->m_strPeerAddress;
					m_DataSocket.SendTo(Message, Message.GetLength(), 
						nPeerPort, PeerAddress);
				}
			}
			else								//对单个用户
			{
				for(i=0; i<m_ClientList.GetCount(); i++)
				{
					m_pClientSocket = m_ClientList.GetAt(m_ClientList.FindIndex(i));
					if(m_pClientSocket->m_strNickname == MsgTo)
					{
						Message = "管理员 悄悄地 对你说: " + Message;
						nPeerPort = m_pClientSocket->m_nUDPPort;
						PeerAddress = m_pClientSocket->m_strPeerAddress;
						m_DataSocket.SendTo(Message, Message.GetLength(), 
							nPeerPort, PeerAddress);
						break;
					}
				}
			}
		}
		else						//公聊
		{
			for(i=0; i<m_ClientList.GetCount(); i++)
			{
				GetDlgItemText(IDC_MESSAGEINPUT, Message);
				m_pClientSocket = m_ClientList.GetAt(m_ClientList.FindIndex(i));
				TempMessage = Message;
				Message = "系统公告:" + TempMessage;
				nPeerPort = m_pClientSocket->m_nUDPPort;
				PeerAddress = m_pClientSocket->m_strPeerAddress;
				m_DataSocket.SendTo(Message, Message.GetLength(), 
					nPeerPort, PeerAddress);
			}
		}
		
	}
	CString clear="";
	SetDlgItemText(IDC_MESSAGEINPUT, clear);

}

void CServerDlg::OnKick() 
{
	// TODO: Add your control notification handler code here
//	CListBox *pListBox = GetDlgItemText(IDC_MEMBERLIST);
	CClientSocket *m_pDelSocket, *m_pClientSocket;
	CListBox *pList = (CListBox *)GetDlgItem(IDC_MEMBERLIST);
	CString Message, MsgTo;
	CString str1,Port;
	int i=0;int j=0;
	GetDlgItemText(IDC_MEMBERSELECT, MsgTo);
	if(MsgTo!="所有人")
	{
		for(i=0; i<m_ClientList.GetCount(); i++)
		{
			m_pDelSocket = m_ClientList.GetAt(m_ClientList.FindIndex(i));
			if(m_pDelSocket->m_strNickname == MsgTo)
			{
				i=j;
				break;
			}
		}
		
		for(i=0; i<m_ClientList.GetCount(); i++)
		{
			m_pClientSocket = m_ClientList.GetAt(m_ClientList.FindIndex(i));
			Message.Format("%d", m_pDelSocket->m_nUDPPort);
			Message = "Del" + m_pDelSocket->m_strPeerAddress + "/"
			+ Message + "/" + m_pDelSocket->m_strNickname;
			m_pClientSocket->Send(Message, Message.GetLength());
		}
//		
		int index=pList->FindString(0, MsgTo);
		pList->DeleteString(index);
		m_ClientList.RemoveAt(m_ClientList.FindIndex(index));
//		m_ClientList.DeleteItem(j);
		
		CRichEditCtrl *pRichEdit = (CRichEditCtrl *)GetDlgItem(IDC_MESSAGEDISP);
		pRichEdit->GetWindowText(str1);
		Port.Format("%d", m_pDelSocket->m_nUDPPort);
		str1 += "\r\n来自" + m_pDelSocket->m_strPeerAddress + ":" + Port+"的朋友被管理员请出聊天室!";
		str1 += "\r\n***** " + MsgTo + " 离开了聊天室 *****";
		pRichEdit->SetWindowText(str1);
		m_pDelSocket->Close();

	}
	m_MemCounts=m_ClientList.GetCount();
	UpdateData(false);
}

void CServerDlg::SetColour(CRichEditCtrl *rich,LPCTSTR lpszMessage,COLORREF clr)
{
	CHARFORMAT cf;
	ZeroMemory(&cf, sizeof(CHARFORMAT));
	cf.cbSize=sizeof(CHARFORMAT);   
	cf.dwMask=CFM_COLOR|CFM_FACE|CFM_SIZE|CFM_BOLD|CFM_ITALIC|CFM_UNDERLINE;   
	if(cf.dwEffects&CFE_AUTOCOLOR)cf.dwEffects-=CFE_AUTOCOLOR;   
	 //Get a color from the common color dialog.   
	cf.crTextColor=clr;   
	cf.dwMask=CFM_COLOR;   
	rich->SetSelectionCharFormat(cf);   
	rich->ReplaceSel(lpszMessage);   

}

void CServerDlg::OnBUTTONSaverecord() 
{
	// TODO: Add your control notification handler code here
	CFileDialog savefiledlg(FALSE,NULL,NULL,OFN_OVERWRITEPROMPT|OFN_ALLOWMULTISELECT,"All Files (*.*)|*.*||",NULL);
	if(savefiledlg.DoModal()==IDOK)
	{
		CFile sfile;
		sfile.Open(savefiledlg.GetPathName(), CFile::modeCreate|CFile::modeWrite|CFile::typeBinary);
		CString record="";
		GetDlgItemText(IDC_MESSAGEDISP, record);
		long writelength=record.GetLength(); 
		sfile.Write(record,writelength);
		sfile.Close();
		//MessageBox(Framest);
	}
	
}

⌨️ 快捷键说明

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