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

📄 messageserverdlg.cpp

📁 我为聊狂的聊天软件,又一款UDP聊天软件
💻 CPP
📖 第 1 页 / 共 2 页
字号:
//***    软件名称:我为聊狂信息服务器
//***    文件名称:MessageServerDlg.cpp
//***   功能:实现用户信息的转发
//***    软件开发:顾加平
//***    邮箱地址:jiapingboy@163.com
//以下代码全是作者个人写的,版权属于作者个人,不准随意复制传播!!

#include "stdafx.h"
#include "MessageServer.h"
#include "MessageServerDlg.h"
#include <afxmt.h>   //为了使用互斥体变量


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

#define PORT (unsigned short)9614
#define WM_SYSTEMTRAY WM_USER+1
#define ID_SYSTEMTRAY WM_USER+2
/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

//******************************************
//*   定义共享数据结构

send_Info   send_Data;  //发送数据
CList<socket_Info, socket_Info&> socket_List;
CList<CUserInfo, CUserInfo&> user_List;
CMutex mutex;       //互斥体变量
//******************************************


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()

/////////////////////////////////////////////////////////////////////////////
// CMessageServerDlg dialog

CMessageServerDlg::CMessageServerDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CMessageServerDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CMessageServerDlg)
		// 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);
}

void CMessageServerDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CMessageServerDlg)
		// NOTE: the ClassWizard will add DDX and DDV calls here
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CMessageServerDlg, CDialog)
	//{{AFX_MSG_MAP(CMessageServerDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_MESSAGE(WM_SYSTEMTRAY, OnSystemTray)
	ON_BN_CLICKED(IDC_RUN, OnRun)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CMessageServerDlg message handlers

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


//服务器开始运行
void CMessageServerDlg::OnRun() 
{
	//初始化网络
	Net_Init();

	
	//设置托盘
	nid.cbSize=sizeof(NOTIFYICONDATA);
	nid.hWnd=m_hWnd;
	nid.uID=ID_SYSTEMTRAY;
	nid.uFlags=NIF_MESSAGE|NIF_ICON|NIF_TIP;
	nid.uCallbackMessage=WM_SYSTEMTRAY;
	nid.hIcon=AfxGetApp()->LoadIcon(IDR_MAINFRAME);
	sprintf(nid.szTip ,"%s\n%s", "我为聊狂通信服务器", m_strServerInfo);
	::Shell_NotifyIcon(NIM_ADD,&nid);
	ShowWindow(SW_HIDE);

	//开始循环接受用户的联入
	WaitConnect();

}


//初始化网络
void CMessageServerDlg::Net_Init()
{
	WSADATA wsaData;
	int err;
	hostent *myEnt=NULL;
	char chName[256];

	err = WSAStartup(MAKEWORD(1,1), &wsaData);
	//如果出错
	if(err!=0)
	{
		MessageBox(_T("无法初始化网络!"), _T("我为聊狂通信服务器"), MB_ICONERROR);
		return;
	}
	
	err =::gethostname (chName, 256);   //取得主机名
	if(err==0)
	{
		//初始化网络地址字段
		m_servSockAddr.sin_family = AF_INET;
		m_servSockAddr.sin_port =htons(PORT);
		m_servSockAddr.sin_addr.s_addr = htonl(INADDR_ANY);

		m_servSocket = socket(AF_INET, SOCK_STREAM, 0);
		
		//如果socket调用失败
		if(m_servSocket == INVALID_SOCKET)
		{
			MessageBox(_T("socket 函数调用失败!"), _T("我为聊狂通信服务器"), MB_ICONERROR);
			return;
		}
		else
		{
			err =bind(m_servSocket, (sockaddr *)&m_servSockAddr, sizeof(m_servSockAddr));
			
			//如果无法进行梆定
			if(err == SOCKET_ERROR)
			{				
				MessageBox(_T("bind 函数调用失败!"), _T("我为聊狂通信服务器"), MB_ICONERROR);
				return;
			}
			//取得主机的一些网络信息
			myEnt =::gethostbyname (chName);
			if(myEnt != NULL)
			{
				m_strServerInfo.Format ("Server Name:%s\nServerIP:%d.%d.%d.%d",
					myEnt->h_name , 
					(unsigned char)myEnt->h_addr_list [0][0],
					(unsigned char)myEnt->h_addr_list [0][1],
					(unsigned char)myEnt->h_addr_list [0][2],
					(unsigned char)myEnt->h_addr_list [0][3]);
			}

			//开始侦听
			err = listen(m_servSocket, 5);
			if(err ==SOCKET_ERROR)
			{
				MessageBox(_T("listen 函数调用失败!"), _T("我为聊狂通信服务器"), MB_ICONERROR);
				return;
			}  //end if(err ==SOCKET_ERROR)
		} //end else
	}  //end if(err==0)
	return;
}


//托盘响应函数
LRESULT CMessageServerDlg::OnSystemTray(WPARAM wParam, LPARAM lParam)
{
	return TRUE;
}


//不断等待用户的连入
void CMessageServerDlg::WaitConnect()
{
	int len;
	char recvTemp[50];
	char recvBuff[500];
	int i;

	len = sizeof(sockaddr);
	
	while(1)
	{
		int i_myIcon;   //接入用户的图标

		//等待用户连入
		m_clientSocket = ::accept (m_servSocket, (sockaddr *)&m_clientSockAddr, &len);
		
		if(m_clientSocket == INVALID_SOCKET)
		{
			MessageBox(_T("用户接入出错!"), _T("我为聊狂通信服务器"), MB_ICONERROR);
			continue;
		}
		
		
		//读取用户的一些信息
		i =recv(m_clientSocket, recvBuff, 500, 0);

		if(i>0)
		{
			recvBuff[i] = '\0';

			GetUserInfo(recvBuff);
			i_myIcon = userInfo.m_imyIcon ;
			user_List.AddTail (userInfo);  //添加用户结点

			sprintf(recvTemp, "%s\0", userInfo.m_strPetName );
			

			//查找是否有相同的妮称
			socket_Info tempSocketInfo;
			POSITION pos;
			pos = socket_List.GetHeadPosition ();
			if(pos!=NULL)
			{
				do
				{
					tempSocketInfo = socket_List.GetNext (pos);
					
					if(tempSocketInfo.petName .Compare (recvTemp) ==0)
					{
						//如果相同
						send(m_clientSocket, "repeat", strlen("repeat") +1, 0);
						//关闭连接
						closesocket(m_clientSocket);
						continue;
					}
				}while(pos!=NULL);
			}
	

			//返回成功
			send(m_clientSocket, "success", strlen("success")+1, 0);
		}


		CWinThread *hHandle_s, *hHandle_r;
		
		//启动发送线程
		hHandle_s = AfxBeginThread(SendThread, (LPVOID)m_clientSocket);
		hHandle_s->SuspendThread ();   //挂起线程

		//保存该用户的相应线程数据
		socket_Info tempInfo;
		tempInfo.client_Socket =m_clientSocket;
		tempInfo.petName .Format ("%s", recvTemp);
		tempInfo.thread =hHandle_s;
		socket_List.AddTail (tempInfo);


		//启动接收线程
		hHandle_r = AfxBeginThread(RecvThread, (LPVOID)m_clientSocket);

		if(hHandle_r == NULL)
		{
			MessageBox(_T("无法客户接收进程!"), _T("我为聊狂通信服务器"), MB_ICONERROR);
			continue;
		}

⌨️ 快捷键说明

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