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

📄 tsdlg.cpp

📁 一个类似QQ的聊天程序--服务器.利用WINSOCK编写,在VISUAL C++调试通过
💻 CPP
字号:
// TsDlg.cpp : implementation file
//

#include "stdafx.h"
#include "Source.h"
#include "Ts.h"
#include "TsDlg.h"
#include "Msg.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()

/////////////////////////////////////////////////////////////////////////////
// CTsDlg dialog

CTsDlg::CTsDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CTsDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CTsDlg)
	m_nPort = 6000;
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_QQ);
}

void CTsDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CTsDlg)
	DDX_Control(pDX, IDC_LIST_MESSAGE, m_listMsg);
	DDX_Control(pDX, IDC_LIST_ONLINE, m_listOnline);
	DDX_Text(pDX, IDC_EDIT_PORT, m_nPort);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CTsDlg, CDialog)
	//{{AFX_MSG_MAP(CTsDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BUTTON_LISTEN, OnButtonListen)
	ON_BN_CLICKED(IDOK, OnClose)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CTsDlg message handlers

BOOL CTsDlg::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
	
	return TRUE;  // return TRUE  unless you set the focus to a control
}

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

void CTsDlg::OnButtonListen() 
{
	// TODO: Add your control notification handler code here
	for(int r=0;r<250;r++)                 //初始化ID池
		client[r]=0;
	UpdateData(TRUE);
	m_pLSocket=new CLSocket(this);
	if(!m_pLSocket->Create(m_nPort))
	{
		delete m_pLSocket;
		m_pLSocket=NULL;
		AfxMessageBox("创建监听套接字错误");
		return;
	}
	if(!m_pLSocket->Listen())
	{
		delete m_pLSocket;
		m_pLSocket=NULL;
		AfxMessageBox("启动监听错误");
		return;
	}

	GetDlgItem(IDC_EDIT_PORT)->EnableWindow(FALSE);
	GetDlgItem(IDC_BUTTON_LISTEN)->EnableWindow(FALSE);
	GetDlgItem(IDOK)->EnableWindow(TRUE);
}


void CTsDlg::OnAccept()
{
	CCSocket *pSocket=new CCSocket(this);
	if(m_pLSocket->Accept(*pSocket))
	{
		pSocket->Initialize();               //为该套接字绑定规档对象
	}
	else
		delete pSocket;
}

void CTsDlg::OnReceive(CCSocket* pSocket)
{
	POSITION pos;
	static CMsg msg;
	do
	{
		pSocket->ReceiveMessage(&msg);
		if(msg.m_strText.m_ID==255 && msg.m_strText.m_ID==msg.m_strText.s_ID)   //客户注册信息
		{
			p=new struct people;
			for(int tt=1;tt<250;tt++)             //利用全局变量给客户分配ID
			{
				if(client[tt]==0)
				{
					p->ID=tt;
					client[tt]=1;
					break;
				}
			}
			p->name=msg.m_strText.msg;
			p->pSocketclient=pSocket;
			m_Online.AddTail(p);           //添加到在线人员列表

			m_listOnline.InsertString(0,p->name);

			msg.m_strText.m_ID= p->ID;      //分配给该客户的ID
			msg.m_strText.s_ID=256;
			msg.m_strText.msg=p->name;
			Toclient(&msg,pSocket);        //给该客户发送他的ID

			msg.m_strText.m_ID=p->ID;
			msg.m_strText.s_ID=257;
			msg.m_strText.msg=p->name;
			backClients(&msg,pSocket);    //通知每个客户有人上线了
		}
		else if(msg.m_strText.s_ID==258)
		{
			int aa=msg.m_strText.m_ID;          //请求更新的人的ID
			for(pos=m_Online.GetHeadPosition();pos!=NULL;)
			{
				struct people *pp=(struct people *)m_Online.GetNext(pos);
				if(pp->ID!=aa)                                     
				{
					msg.m_strText.m_ID=pp->ID;
					msg.m_strText.s_ID=258;
					msg.m_strText.msg=pp->name;
					msg.m_bClose=FALSE;
					pSocket->SendMessage(&msg);        //转发消息给该客户
				}
			}
		}
		else if(msg.m_strText.m_ID==259)                          //在消息列表里显示有人退出聊天室
		{
			m_listMsg.InsertString(0,msg.m_strText.msg);
		}
		else if(msg.m_strText.m_ID != msg.m_strText.s_ID)                                //转发信息到相应的客户
		{
			CString ClinetMsg;
			CString MName;
			CString SName;
			for(pos=m_Online.GetHeadPosition();pos!=NULL;)
			{
				struct people *pp=(struct people *)m_Online.GetNext(pos);
				if(pp->ID==msg.m_strText.m_ID)                    //找到目的客户的ID                 
				{
					MName=pp->name;
					pp->pSocketclient->SendMessage(&msg);         //转发消息给该客户
				}
				if(pp->ID==msg.m_strText.s_ID)
					SName=pp->name;
			}			
			ClinetMsg.Format("%s 对 %s说: %s",SName,MName,msg.m_strText.msg);
			m_listMsg.InsertString(0,ClinetMsg);
		}
		if(msg.m_bClose)                                           //有人退出了
		{
			pSocket->Close();
			client[msg.m_strText.s_ID]=0;	                       //释放ID
			POSITION pos,temp;
			struct people *pSock;
			m_listOnline.ResetContent();                          //先清除在线人员列表中的所有内容
			for(pos=m_Online.GetHeadPosition();pos!=NULL;)
			{
				temp=pos;
				pSock=(struct people*)m_Online.GetNext(pos);
				if(pSock->pSocketclient==pSocket)
				{
					msg.m_strText.m_ID=pSock->ID;         //退出人的ID
					msg.m_strText.s_ID=259;
					msg.m_strText.msg=pSock->name;
					msg.m_bClose=FALSE;
					m_Online.RemoveAt(temp);               //从在线人员列表中删除
				}
			}
			for(pos=m_Online.GetHeadPosition();pos!=NULL;)        //通知每个在线客户有人退出并使其更新显示列表
			{
				struct people *pp=(struct people *)m_Online.GetNext(pos);
				pp->pSocketclient->SendMessage(&msg);
				m_listOnline.InsertString(0,pp->name);
			}		
			delete pSocket;                
			break;
		}
	}while(!pSocket->m_pArchiveIn->IsBufferEmpty());
}

void CTsDlg::Toclient(CMsg *pMsg,CCSocket *pSocket)
{
	pSocket->SendMessage(pMsg);                          //发送给刚刚上线的客户
}

void CTsDlg::backClients(CMsg *pMsg,CCSocket *pSocket)
{
	for(POSITION pos=m_Online.GetHeadPosition();pos!=NULL;)
	{
		struct people *pp=(struct people *)m_Online.GetNext(pos);
		if(pp->pSocketclient!=pSocket)                   //发送给其它的客户
			pp->pSocketclient->SendMessage(pMsg);
	}
}

void CTsDlg::OnClose() 
{
	// TODO: Add your control notification handler code here
	CMsg msg;
	msg.m_strText.msg="服务器终止服务!";
	delete m_pLSocket;
	m_pLSocket=NULL;
	while(!m_Online.IsEmpty())
	{
		CCSocket *pSocket=(CCSocket*)m_Online.RemoveHead();
		pSocket->SendMessage(&msg);
		delete pSocket;
	}
	while(m_listMsg.GetCount()!=0)
		m_listMsg.DeleteString(0);
	while(m_listOnline.GetCount()!=0)
		m_listOnline.DeleteString(0);

	for(int r=0;r<250;r++)                 // 恢复初始ID池
		client[r]=0;

	GetDlgItem(IDC_EDIT_PORT)->EnableWindow(TRUE);
	GetDlgItem(IDC_BUTTON_LISTEN)->EnableWindow(TRUE);
	GetDlgItem(IDOK)->EnableWindow(FALSE);
}

⌨️ 快捷键说明

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