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

📄 serverhdlg.cpp

📁 这是一个网络编程的小型例子
💻 CPP
字号:
// serverHDlg.cpp : implementation file
//

#include "stdafx.h"
#include "serverH.h"
#include "serverHDlg.h"

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

/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About
SOCKET sockserver1,sockserver2,tmpsocket1,tmpsocket2,socket1,socket2;
sockaddr_in srvsockaddr1,srvsockaddr2;
CWinThread *threadlistener1,*threadrecvsend1;
CWinThread *threadlistener2,*threadrecvsend2;
UINT RecvSendDataThread1(LPVOID lParam);
UINT serverListenThread1(LPVOID lParam);
UINT RecvSendDataThread2(LPVOID lParam);
UINT serverListenThread2(LPVOID lParam);
bool srvState=true;
CUIntArray array1,array2;
LPCTSTR ncard1="1#网卡";
LPCTSTR ncard2="2#网卡";


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

/////////////////////////////////////////////////////////////////////////////
// CServerHDlg dialog

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

void CServerHDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CServerHDlg)
	DDX_Control(pDX, IDC_LIST3, m_conmsg2);
	DDX_Control(pDX, IDC_COMBO1, m_comboNcard);
	DDX_Control(pDX, IDC_BtnClear, m_btnclear);
	DDX_Control(pDX, IDC_LIST1, m_conmsg);
	DDX_Control(pDX, IDC_BtnSetIP, m_btnIPSet);
	DDX_Control(pDX, IDC_EDITMSG, m_editmsg);
	DDX_Control(pDX, IDC_EDIT3, m_ip1);
	DDX_Control(pDX, IDC_EDIT4, m_ip2);
	DDX_Control(pDX, IDC_LIST2, m_recvText);
	DDX_Control(pDX, IDOK, m_OK);
	DDX_Control(pDX, IDCANCEL, m_cancel);
	DDX_Control(pDX, IDC_EDIT2, m_senddata);
	DDX_Control(pDX, IDC_BUTTON1, m_btnsend);
	DDX_Control(pDX, IDC_BUTTON4, m_btnstop);
	DDX_Control(pDX, IDC_BUTTON3, m_btnstart);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CServerHDlg, CDialog)
	//{{AFX_MSG_MAP(CServerHDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BUTTON3, OnButton3StartServer)
	ON_BN_CLICKED(IDC_BUTTON4, OnButton4)
	ON_COMMAND(ID_MENUITEM32772, OnMenuitemQuit)
	ON_BN_CLICKED(IDC_BUTTON1, OnButton1)
	ON_BN_CLICKED(IDC_BtnSetIP, OnBtnSetIP)
	ON_BN_CLICKED(IDC_BtnClear, OnBtnClear)
	ON_BN_CLICKED(IDC_BtnClearMsg, OnBtnClearMsg)
	ON_BN_CLICKED(IDC_BtnClear2, OnBtnClear2)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CServerHDlg message handlers

BOOL CServerHDlg::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
	//版本检查
	WSADATA wsa;
	if(WSAStartup(0x102,&wsa))
	{
		AfxMessageBox("套接字初始化错误!",NULL,MB_OK|MB_ICONSTOP);
		WSACleanup();
		return FALSE;
	}
	if(LOBYTE(wsa.wVersion)!=2 || HIBYTE(wsa.wVersion)!=1)
	{
		AfxMessageBox("版本匹配错误!",NULL,MB_OK||MB_ICONSTOP);
		WSACleanup();
		return FALSE;
	}
	/*
	//得到本地主机名
	char localhostname[100];
	gethostname(localhostname,sizeof(localhostname));
	m_recvText.AddString(localhostname);
	//得到本机IP地址
	struct hostent* hostIP=gethostbyname(localhostname);
	m_recvText.AddString(hostIP->h_addr_list[0]);
	*/
	return TRUE;  // return TRUE  unless you set the focus to a control
}

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

void CServerHDlg::OnOK() 
{
	// TODO: Add extra validation here
	CDialog::OnOK();
	this->CloseWindow();
}

void CServerHDlg::OnCancel() 
{
	// TODO: Add extra cleanup here
	
	CDialog::OnCancel();
}

//数据处理线程函数1
UINT RecvSendDataThread1(LPVOID lParam)
{
	int valRecvData=1;
	char buff[100]; //定义缓冲区
	SOCKET sockthis=tmpsocket1;
	CServerHDlg *dlg=(CServerHDlg*)AfxGetApp()->GetMainWnd();
	while(valRecvData!=SOCKET_ERROR)
	{
		valRecvData=recv(tmpsocket1,buff,sizeof(buff),0);//接收数据
		dlg->m_recvText.AddString(buff);
		buff[0]='\0';
		dlg->SetForegroundWindow();
	}
	return 0;
}
//服务器网络监听函数1
UINT serverListenThread1(LPVOID lParam)
{
	//当前线程进入阻塞状态,等待socket连接
	int nLen=sizeof(srvsockaddr1);
	CServerHDlg *dlg=(CServerHDlg*)AfxGetApp()->GetMainWnd();
	while(true)
	{
		SOCKET sock=accept(sockserver1,(SOCKADDR*)&srvsockaddr1,&nLen);
		socket1=sock;
		//将sock添加到动态数组中
		array1.Add(sock);

		if(sock==INVALID_SOCKET) break;
		char *clientIP=inet_ntoa(srvsockaddr1.sin_addr);
		CString cliIP=CString(clientIP);
		cliIP="客户端IP:"+cliIP;
		dlg->m_conmsg.AddString(cliIP);
		//调用线程
		tmpsocket1=sock;
		threadrecvsend1=AfxBeginThread(RecvSendDataThread1,NULL);
	}
	return 0;
}
//数据处理线程函数2
UINT RecvSendDataThread2(LPVOID lParam)
{
	int valRecvData=1;
	char buff[100]; //定义缓冲区
	SOCKET sockthis=tmpsocket2;
	CServerHDlg *dlg=(CServerHDlg*)AfxGetApp()->GetMainWnd();
	while(valRecvData!=SOCKET_ERROR)
	{
		valRecvData=recv(tmpsocket2,buff,sizeof(buff),0);//接收数据
		dlg->m_recvText.AddString(buff);
		buff[0]='\0';
		dlg->SetForegroundWindow();
	}
	return 0;
}
//服务器网络监听函数2
UINT serverListenThread2(LPVOID lParam)
{
	//当前线程进入阻塞状态,等待socket连接
	int nLen=sizeof(srvsockaddr2);
	CServerHDlg *dlg=(CServerHDlg*)AfxGetApp()->GetMainWnd();
	while(true)
	{
		SOCKET sock=accept(sockserver2,(SOCKADDR*)&srvsockaddr2,&nLen);
		socket2=sock;
		//将sock添加到动态数组中
		array2.Add(sock);

		if(sock==INVALID_SOCKET) break;
		char *clientIP=inet_ntoa(srvsockaddr2.sin_addr);
		CString cliIP=CString(clientIP);
		cliIP="客户端IP:"+cliIP;
		dlg->m_conmsg2.AddString(cliIP);
		//调用线程
		tmpsocket2=sock;
		threadrecvsend2=AfxBeginThread(RecvSendDataThread2,NULL);
	}
	return 0;
}
///

void CServerHDlg::OnButton3StartServer()
{
	// TODO: Add your control notification handler code here
	/////绑定第一块网卡
	sockserver1=socket(AF_INET,SOCK_STREAM,0);
	//设置socket在指定的IP地址上监听
	CString strIP=this->strIP1;
	DWORD dwIP=inet_addr(strIP);
	srvsockaddr1.sin_addr.s_addr=dwIP;
	srvsockaddr1.sin_family=AF_INET;
	srvsockaddr1.sin_port=20001;
	//绑定
	if (bind(sockserver1,(sockaddr*)&srvsockaddr1,sizeof(srvsockaddr1)))
	{
		m_conmsg.AddString("IP地址1绑定错误!");
		srvState=false;
	}
	else
		m_conmsg.AddString("IP地址1绑定成功!");
	//绑定第二块网卡
	sockserver2=socket(AF_INET,SOCK_STREAM,0);
	//设置socket在指定的IP地址上监听
	CString strIP2=this->strIP2;
	DWORD dwIP2=inet_addr(strIP2);
	srvsockaddr2.sin_addr.s_addr=dwIP;
	srvsockaddr2.sin_family=AF_INET;
	srvsockaddr2.sin_port=20002;
	//绑定
	if (bind(sockserver2,(sockaddr*)&srvsockaddr2,sizeof(srvsockaddr2)))
	{
		m_conmsg2.AddString("IP地址2绑定错误!");
		srvState=false;
	}
	else
		m_conmsg2.AddString("IP地址2绑定成功!");

	//开始侦听IP1
	if(listen(sockserver1,20)==SOCKET_ERROR)
	{
		/*CString sMSG;
		sMSG.Format("侦听失败,错误码:%d",WSAGetLastError());
		AfxMessageBox(sMSG);*/
		m_conmsg.AddString("IP地址1侦听出错!");
		srvState=false;
		//return ;
	}
	else
		m_conmsg.AddString("IP地址1正确侦听!");
	//开始侦听IP2
	if(listen(sockserver2,20)==SOCKET_ERROR)
	{
		/*CString sMSG;
		sMSG.Format("侦听失败,错误码:%d",WSAGetLastError());
		AfxMessageBox(sMSG);*/
		m_conmsg2.AddString("IP地址2侦听出错!");
		srvState=false;
	}
	else
		m_conmsg2.AddString("IP地址2正确侦听!");
	//////////////////////////////////////////////////////////////////
	if(srvState==true)
	{
		this->m_btnstart.EnableWindow(false);
	}
	else
		return;

	threadlistener1=::AfxBeginThread(serverListenThread1,NULL);
	threadlistener2=::AfxBeginThread(serverListenThread2,NULL);
}

void CServerHDlg::OnButton4() 
{
	// TODO: Add your control notification handler code here
	int length;
	length=array1.GetSize();
	//char lengthstr[10];
	//_itoa(length,lengthstr,10);	
	//AfxMessageBox(lengthstr);
	while(length>0)
	{
		closesocket((SOCKET)array1[0]);
		array1.RemoveAt(0,1);
		length--;
	}
	length=array2.GetSize();
	while(length>0)
	{
		closesocket((SOCKET)array2[0]);
		array2.RemoveAt(0,1);
		length--;
	}
	closesocket(sockserver1);
	closesocket(sockserver2);
	closesocket(tmpsocket1);
	closesocket(tmpsocket2);
	closesocket(socket1);
	closesocket(socket2);
	m_btnstart.EnableWindow(true);
}

void CServerHDlg::OnMenuitemQuit() 
{
	// TODO: Add your command handler code here
	OnOK();
}

void CServerHDlg::OnButton1() 
{
	// TODO: Add your control notification handler code here
	CString msg;
	m_senddata.GetWindowText(msg);
	/*int i=0;
	SOCKET sockthis;
	while(array1.GetSize()>0)
	{
		sockthis=array1.GetAt(i);
	}*/
	CString ncardstr;
	m_comboNcard.GetWindowText(ncardstr);
	
	if(ncardstr.Compare("1#网卡")==0)
	{
		//AfxMessageBox("相同");
		send(socket1,msg,100,0);
	}
	else
		send(socket2,msg,100,0);
	//send(socket1,msg,100,0);
}

void CServerHDlg::OnBtnSetIP() 
{
	// TODO: Add your control notification handler code here
	CString ip1,ip2;
	m_comboNcard.Clear();
	while(m_comboNcard.GetCount()>0)
	{
		m_comboNcard.DeleteString(0);
	}
	m_ip1.GetWindowText(ip1);
	if(ip1.IsEmpty())
	{
		AfxMessageBox("必须填入IP地址:");
		return;
	}
	this->strIP1=ip1;

	m_comboNcard.AddString(ncard1);

	m_ip2.GetWindowText(ip2);
	if(ip2.IsEmpty())
	{
		this->strIP2=CString("0.0.0.0");
	}
	m_comboNcard.AddString(ncard2);

	m_editmsg.SetWindowText("服务器IP地址已设置");
}

void CServerHDlg::OnBtnClear() 
{
	// TODO: Add your control notification handler code here
	while(m_conmsg.GetCount())
	{
		m_conmsg.DeleteString(0);
	}
}

void CServerHDlg::OnBtnClearMsg() 
{
	// TODO: Add your control notification handler code here
	while(m_recvText.GetCount())
	{
		m_recvText.DeleteString(0);
	}
}

void CServerHDlg::OnBtnClear2() 
{
	// TODO: Add your control notification handler code here
	while(m_conmsg2.GetCount())
	{
		m_conmsg2.DeleteString(0);
	}
}

⌨️ 快捷键说明

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