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

📄 serverdlg.cpp

📁 C/S模式的局域网计时程序
💻 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)
		// 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 CServerDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CServerDlg)
	DDX_Control(pDX, IDC_IPADDRESS2, m_ip2);
	DDX_Control(pDX, IDC_IPADDRESS1, m_ip1);
	DDX_Control(pDX, IDC_MYLIST, m_list);
	//}}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_CONNECT, OnConnect)
	ON_BN_CLICKED(IDC_DISCONNECT, OnDisconnect)
	ON_MESSAGE(US_SOCK,OnListenSockMessage)
	ON_WM_TIMER()
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

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

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

	//初始化按钮状态
	GetDlgItem(IDC_CONNECT)->EnableWindow(true);
	GetDlgItem(IDC_DISCONNECT)->EnableWindow(false);

	//初始化List控件
	m_list.InsertColumn ( 0, _T("编号"), LVCFMT_LEFT,64 );
	m_list.InsertColumn ( 1, _T("上机时间"), LVCFMT_CENTER,170 );
	m_list.InsertColumn ( 2, _T("IP地址"), LVCFMT_CENTER,170 );
	m_list.InsertColumn ( 3, _T("是否在线"), LVCFMT_CENTER,64 );
	m_list.SetExtendedStyle ( LVS_EX_FULLROWSELECT  |LVS_EX_GRIDLINES );

	//初始化时间变量
	for(int i = 0;i < 100;i++)
		m_StopTime[i] = CTime::GetCurrentTime() - CTime::GetCurrentTime();

	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::OnConnect() 
{
	// TODO: Add your control notification handler code here
	int flag = 1;
	m_ip1.GetAddress(ip1[0],ip1[1],ip1[2],ip1[3]);
	m_ip2.GetAddress(ip2[0],ip2[1],ip2[2],ip2[3]);

	if(m_ip1.IsBlank() || m_ip2.IsBlank())
		flag = 0;
	else
	{
		for(int i = 0;i < 4;i++)
		{
			if(ip1[i] < 0 || ip2[i] < 0 || ip1[i] >= 255 || ip2[i] >= 255
				|| (i != 3 && ip1[i] != ip2[i])
				|| (i == 4 && ip1[i] >= ip2[i])
				)
			{
				flag = 0;
				break;
			}
		}
	}

	if(!flag)
	{
		MessageBox("IP地址段输入有误!");
		return;
	}

	m_ClientNum = ip2[3] - ip1[3] + 1;
	this->ChangeList();

	if(!InitSocket())
		return;
	SetTimer(1,500,0);

	GetDlgItem(IDC_CONNECT)->EnableWindow(false);
	GetDlgItem(IDC_DISCONNECT)->EnableWindow(true);
	GetDlgItem(IDC_IPADDRESS1)->EnableWindow(false);
	GetDlgItem(IDC_IPADDRESS2)->EnableWindow(false);
}

void CServerDlg::OnDisconnect() 
{
	// TODO: Add your control notification handler code here
	if(this->sock_listen)
	{
		char buf[1];
		buf[0] = '1';
		for(int i = 0;i < this->m_ClientNum;i++)
			send(this->sock_client[i],buf,1,0);

		closesocket(this->sock_listen);
		this->sock_listen = 0;
	}
	KillTimer(1);
	GetDlgItem(IDC_CONNECT)->EnableWindow(true);
	GetDlgItem(IDC_DISCONNECT)->EnableWindow(false);
	GetDlgItem(IDC_IPADDRESS1)->EnableWindow(true);
	GetDlgItem(IDC_IPADDRESS2)->EnableWindow(true);
}

void CServerDlg::ChangeList()
{
	CString s;
	m_list.DeleteAllItems();

	for(int i = 0;i < m_ClientNum;i++)
	{
		if(i < 9)
			s.Format("0%d",i+1);
		else
			s.Format("%d",i+1);
		m_list.InsertItem(i,_T(s));

		m_list.SetItemText(i,1,m_StopTime[i].Format("%H:%M:%S"));

		s.Format("%d.%d.%d.%d",ip1[0],ip1[1],ip1[2],ip1[3] + i);
		m_list.SetItemText(i,2,_T(s));

		m_list.SetItemText(i,3,"否");
	}	
}

BOOL CServerDlg::InitSocket()
{
	struct sockaddr_in server;
	WSADATA wsa;
	WSAStartup(wVersionRequested, &wsa);

	//初始化侦听
	///////////////////////////////////////////////////////
	if(sock_listen != 0)
	{
		closesocket(sock_listen);
		sock_listen = 0;
	}

	sock_listen = socket(AF_INET, SOCK_STREAM, 0);
	if(sock_listen == INVALID_SOCKET)
	{
		sock_listen = 0;
		MessageBox("侦听失败!");
		WSACleanup();
		return false;
	}

	//绑定
	server.sin_family = AF_INET;
	server.sin_port = htons((u_short)5432);
	server.sin_addr.s_addr = INADDR_ANY;

	if(bind(sock_listen, (LPSOCKADDR)&server, sizeof(server)) == SOCKET_ERROR)
	{
		MessageBox("绑定失败!");
		closesocket(sock_listen);
		sock_listen = 0;
		WSACleanup();
		return false;
	}

	//非阻塞等待
	if(WSAAsyncSelect(sock_listen, m_hWnd, US_SOCK, FD_ACCEPT | FD_READ | FD_CLOSE) == SOCKET_ERROR)
	{
		MessageBox("选择侦听事件错误!");
		closesocket(sock_listen);
		WSACleanup();
		return false;
	}

	//侦听
	if(listen(sock_listen, SOMAXCONN) == SOCKET_ERROR)
	{
		MessageBox("侦听错误!");
		closesocket(sock_listen);
		WSACleanup();
		return false;
	}
	return true;
}

void CServerDlg::OnListenSockMessage(WPARAM wParam, LPARAM lParam)
{
	
	switch(WSAGETSELECTEVENT(lParam))
	{
		case FD_ACCEPT:
			{
				SOCKET s;
				SOCKADDR_IN client;
				int iAddrSize=sizeof(client);
				s = accept(sock_listen, (SOCKADDR *)&client, &iAddrSize);

				if(s == INVALID_SOCKET)
				{
					MessageBox("接受连接错误!");
					closesocket(sock_listen);
					WSACleanup();
					return;
				}

				int IP[4];
				IP[0] = client.sin_addr.S_un.S_un_b.s_b1;
				IP[1] = client.sin_addr.S_un.S_un_b.s_b2;
				IP[2] = client.sin_addr.S_un.S_un_b.s_b3;
				IP[3] = client.sin_addr.S_un.S_un_b.s_b4;

				int n;
				if(IP[0] == ip1[0] && IP[1] == ip1[1] && 
					IP[2] == ip1[2] && IP[3] >= ip1[3] && IP[3] <= ip2[3])
				{
					n = IP[3] - ip1[3];
					sock_client[n] = s;
				}
				else return;

				//初始化连接时间
				m_RecvTime[n] = CTime::GetCurrentTime();
				//改变列表值和颜色
				m_list.SetItemText(n,3,"是");

				m_StartTime[n] = CTime::GetCurrentTime();
				m_OnLine[n] = 1;
				
			}
			break;
		case FD_CLOSE:
			{
				for(int i = 0;i < m_ClientNum && sock_client[i] != wParam;i++) ;

				//改变列表值
				m_list.SetItemText(i,3,"否");

				m_StopTime[i] = CTime::GetCurrentTime() - m_StartTime[i] + m_StopTime[i];
				m_OnLine[i] = 0;
			
			}
			break;
	}
	
}

void CServerDlg::OnTimer(UINT nIDEvent) 
{
	// TODO: Add your message handler code here and/or call default
	//客户端判断
	CTimeSpan CurTime;
	CTime time = CTime::GetCurrentTime();

	//add
	for(int i = 0;i < 100;i++)
	{
		if(m_OnLine[i] == 1)
		{
			if(time - m_RecvTime[i] >= 10)
			{
				//改变列表值
				m_list.SetItemText(i,3,"否");
				m_StopTime[i] = time - m_StartTime[i] + m_StopTime[i];
				m_OnLine[i] = 0;
				continue;
			}
			CurTime = time - m_StartTime[i] + m_StopTime[i];
			//列表计时
			m_list.SetItemText(i,1,CurTime.Format("%H:%M:%S"));
		}
	}

	CDialog::OnTimer(nIDEvent);
}

⌨️ 快捷键说明

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