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

📄 tcpnetkitdlg.cpp

📁 wince系统下的网络编程
💻 CPP
字号:
// TCPNetKitDlg.cpp : implementation file
//

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

/////////////////////////////////////////////////////////////////////////////
// CTCPNetKitDlg dialog

CTCPNetKitDlg::CTCPNetKitDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CTCPNetKitDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CTCPNetKitDlg)
		// 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 CTCPNetKitDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CTCPNetKitDlg)
	DDX_Control(pDX, IDC_EDIT_CLIENT_LOG, m_ctrlEditClientLog);
	DDX_Control(pDX, IDC_EDIT_SERVER_LOG, m_ctrlEditServerLog);
	DDX_Control(pDX, IDC_LIST_CONNECTIONS, m_ctrlListConnections);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CTCPNetKitDlg, CDialog)
	//{{AFX_MSG_MAP(CTCPNetKitDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_WM_DESTROY()
	ON_BN_CLICKED(IDC_START_SERVER, OnStartServer)
	ON_BN_CLICKED(IDC_CONNECT, OnConnect)
	ON_MESSAGE(WM_STATUS_CHANGED,OnStatusChangedMsg)
	ON_MESSAGE(WM_DATA_ARRIVED,OnDataArrivedMsg)
	ON_BN_CLICKED(IDC_CLIENT_SEND, OnClientSend)
	ON_BN_CLICKED(IDC_CLEAR_SERVER_LOG, OnClearServerLog)
	ON_BN_CLICKED(IDC_CLEAR_CLIENT_LOG, OnClearClientLog)
	ON_BN_CLICKED(IDC_CLEAR_SEND, OnClearSend)
	ON_NOTIFY(NM_CLICK, IDC_LIST_CONNECTIONS, OnClickListConnections)
	ON_BN_CLICKED(IDC_SERVER_DISCONNECT, OnServerDisconnect)
	ON_BN_CLICKED(IDC_SERVER_SEND, OnServerSend)
	ON_BN_CLICKED(IDC_CLEAR_SERVER_SEND, OnClearServerSend)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CTCPNetKitDlg message handlers

BOOL CTCPNetKitDlg::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
	//1.初始化变量
	m_psockServer=new CTCPSocket(TCP_SOCKET_SERVER);
	m_psockClient=new CTCPSocket(TCP_SOCKET_CLIENT);
	//2.获取本机的IP和计算机名
	GetLocalHostName(m_strLocalName);
	GetIpAddress(m_strLocalName,m_strLocalIP);
	SetDlgItemText(IDC_EDIT_IP_LOCAL,m_strLocalIP);
	SetDlgItemText(IDC_EDIT_IP_REMOTE,m_strLocalIP);
	//3.设置端口
	m_nPortLocal=1234;
	m_nPortRemote=1234;
	CString Port;
	Port.Format("%d",m_nPortLocal);
	SetDlgItemText(IDC_EDIT_PORT_LOCAL,Port);
	Port.Format("%d",m_nPortRemote);
	SetDlgItemText(IDC_EDIT_PORT_REMOTE,Port);
	//4.初始化表头
	m_ctrlListConnections.InsertColumn(0,"IP",LVCFMT_LEFT,120,-1);
	m_ctrlListConnections.InsertColumn(1,"序号",LVCFMT_LEFT,50,-1);
	m_ctrlListConnections.SetExtendedStyle(LVS_EX_FULLROWSELECT);
	//5.状态变量
	m_bServerCreated=FALSE;
	m_bClientConnected=FALSE;
	m_nCurrentSelect=-1;
	
	return TRUE;  // return TRUE  unless you set the focus to a control
}

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

BOOL CTCPNetKitDlg::PreTranslateMessage(MSG* pMsg) 
{
	//防止按下Esc或Enter键后退出
	if(pMsg->message==WM_KEYDOWN)
	{
		//if(pMsg->wParam==VK_RETURN) return TRUE;
		if(pMsg->wParam==VK_ESCAPE) return TRUE;
	}
	
	return CDialog::PreTranslateMessage(pMsg);
}

void CTCPNetKitDlg::OnOK() 
{	
	CDialog::OnOK();
	DestroyWindow();
}

void CTCPNetKitDlg::OnCancel() 
{
	CDialog::OnCancel();
	DestroyWindow();
}

void CTCPNetKitDlg::OnDestroy() 
{
	CDialog::OnDestroy();
	
	delete m_psockServer;
	delete m_psockClient;
}

//获得本地计算机名称
int CTCPNetKitDlg::GetLocalHostName(CString &sLocalName)
{
	char szLocalName[256];
	int nRetCode;
	nRetCode=gethostname(szLocalName,sizeof(szLocalName));
	if(nRetCode!=0)
	{
		//产生错误
		sLocalName=_T("没有取得");
		return GetLastError();
	}
	sLocalName=szLocalName;
	return 0;
}

//获得本机IP地址
int CTCPNetKitDlg::GetIpAddress(const CString &sLocalName, CString &sIpAddress)
{
	struct hostent FAR * lpHostEnt=gethostbyname(sLocalName);
	if(lpHostEnt==NULL)
	{
		//错误
		sIpAddress=_T("");
		return GetLastError();
	}
	//获取IP地址
	LPSTR lpAddr=lpHostEnt->h_addr_list[0];
	if(lpAddr)
	{
		struct in_addr inAddr;
		memmove(&inAddr,lpAddr,4);
		//转换为标准格式
		sIpAddress=inet_ntoa(inAddr);
		if(sIpAddress.IsEmpty())
		{
			sIpAddress=_T("没有取得");
		}
	}
	return 0;
}

void CTCPNetKitDlg::OnStartServer() 
{
	CString Port;
	GetDlgItemText(IDC_EDIT_PORT_LOCAL,Port);
	m_nPortLocal=atoi(Port.GetBuffer(0));

	if(m_nPortLocal<0||m_nPortLocal>65535)
	{
		AfxMessageBox("请输入正确的端口!");
		return;
	}

	if(!m_bServerCreated)
	{
		if(!m_psockServer->CreateServer(m_nPortLocal,5))
		{
			AfxMessageBox("创建服务器出错!");
			return;
		}
		if(!m_psockServer->StartServer(OnStatusChange,OnDataArrived,(DWORD)this))
		{
			AfxMessageBox("启动服务出错!");
			m_psockServer->Close();
			return;
		}
		m_bServerCreated=TRUE;
		SetDlgItemText(IDC_START_SERVER,_T("停止服务"));
	}
	else
	{
		m_psockServer->Close();
		m_bServerCreated=FALSE;
		SetDlgItemText(IDC_START_SERVER,_T("开始服务"));
		//更新列表
		m_ctrlListConnections.DeleteAllItems();
		m_nCurrentSelect=-1;
	}
	
}

void CTCPNetKitDlg::OnConnect() 
{
	if(!m_bClientConnected)
	{
		CString Port;
		GetDlgItemText(IDC_EDIT_PORT_REMOTE,Port);
		m_nPortRemote=atoi(Port.GetBuffer(0));
		GetDlgItemText(IDC_EDIT_IP_REMOTE,m_strRemoteIP);
		
		if(m_nPortRemote<0||m_nPortRemote>65535)
		{
			AfxMessageBox("请输入正确的端口!");
			return;
		}
		
		if(!m_psockClient->Connect(m_strRemoteIP,m_nPortRemote))
		{
			AfxMessageBox("连接出错!");
			return;
		}
		if(!m_psockClient->StartReceiving(OnStatusChange,OnDataArrived,(DWORD)this))
		{
			AfxMessageBox("启动数据接收出错!");
			m_psockClient->Close();
			return;
		}
		m_bClientConnected=TRUE;
		SetDlgItemText(IDC_CONNECT,_T("断开连接"));

		//更新显示
		CString Status;
		Status=m_strRemoteIP+"连接"+"\r\n";
		AddMessage(Status,1);
	}
	else
	{
		m_psockClient->Close();
		m_bClientConnected=FALSE;
		SetDlgItemText(IDC_CONNECT,_T("连接"));
	}
}

void CTCPNetKitDlg::OnStatusChange(char *data,int length,DWORD userdata)
{
	CTCPNetKitDlg *pWnd=(CTCPNetKitDlg *)userdata;
	::SendMessage(pWnd->m_hWnd,WM_STATUS_CHANGED,(WPARAM)data,LPARAM(length));
}

LONG CTCPNetKitDlg::OnStatusChangedMsg(WPARAM wParam,LPARAM lParam)
{
	//处理收到的数据
	int length=(int)lParam;
	char *data=(char*)wParam;

	CString Status;

	int no;
	int op;
	char n[3];

	//分析数据
	//服务器数据
	if(data[0]=='S')
	{
		Status=CString(data+1).Left(15);
		if(data[16]=='C')
		{
			Status+="连接\r\n";
			op=0;
		}
		if(data[16]=='D')
		{
			Status+="断开\r\n";
			op=1;
		}
		memcpy(n,data+17,3);
		no=atoi(n);
		AddMessage(Status,0);
		Status=CString(data+1).Left(15);
		UpdateList(Status,no,op);
	}

	//客户端数据
	if(data[0]=='C')
	{
		if(data[1]=='D')
		{
			Status=m_strRemoteIP+"断开"+"\r\n";
			AddMessage(Status,1);
		}
	}

	return 0;
}

void CTCPNetKitDlg::OnDataArrived(char *data,int length,DWORD userdata)
{
	CTCPNetKitDlg *pWnd=(CTCPNetKitDlg *)userdata;
	::SendMessage(pWnd->m_hWnd,WM_DATA_ARRIVED,(WPARAM)data,LPARAM(length));
}

LONG CTCPNetKitDlg::OnDataArrivedMsg(WPARAM wParam,LPARAM lParam)
{
	//处理收到的数据
	int length=(int)lParam;
	char *data=(char*)wParam;

	CString Data;

	//分析数据
	if(data[0]=='S')
	{
		Data=CString(data+1).Left(15);
		Data+="发送:";
		Data+=CString(data+21).Left(length-21);
		Data+="\r\n";
		AddMessage(Data,0);
	}

	if(data[0]=='C')
	{
		Data=m_strRemoteIP+"发送:"+CString(data+1).Left(length-1)+"\r\n";
		AddMessage(Data,1);
	}

	return 0;
}

void CTCPNetKitDlg::AddMessage(LPCTSTR msg,int which)
{
	CString Message;

	if(which==0)
	{
		//服务器
		GetDlgItemText(IDC_EDIT_SERVER_LOG,Message);
		Message+=msg;
		SetDlgItemText(IDC_EDIT_SERVER_LOG,Message);
		m_ctrlEditServerLog.SetSel(Message.GetLength(),Message.GetLength());
	}
	else
	{
		//客户端
		GetDlgItemText(IDC_EDIT_CLIENT_LOG,Message);
		Message+=msg;
		SetDlgItemText(IDC_EDIT_CLIENT_LOG,Message);
		m_ctrlEditClientLog.SetSel(Message.GetLength(),Message.GetLength());
	}
}

void CTCPNetKitDlg::OnClientSend() 
{
	CString senddata;
	GetDlgItemText(IDC_EDIT_SEND,senddata);
	int nRet=m_psockClient->SendClient(senddata.GetBuffer(0),senddata.GetLength());

	CString msg;
	//更新客户端显示
	if(nRet>0)
	{
		msg="向"+m_strRemoteIP+"发送:"+senddata.Left(nRet)+"\r\n";
		AddMessage(msg,1);
	}
}

void CTCPNetKitDlg::OnClearServerLog() 
{
	SetDlgItemText(IDC_EDIT_SERVER_LOG,"");
	m_ctrlEditServerLog.SetSel(0,0);
}

void CTCPNetKitDlg::OnClearClientLog() 
{
	SetDlgItemText(IDC_EDIT_CLIENT_LOG,"");
	m_ctrlEditClientLog.SetSel(0,0);
}

void CTCPNetKitDlg::OnClearSend() 
{
	SetDlgItemText(IDC_EDIT_SEND,"");
}

void CTCPNetKitDlg::UpdateList(LPCTSTR Ip,int No,int Operation)
{
	if(Operation==0)
	{
		//连接
		CString no;
		no.Format("%d",No);
		m_ctrlListConnections.InsertItem(m_ctrlListConnections.GetItemCount(),Ip,0);
		m_ctrlListConnections.SetItemText(m_ctrlListConnections.GetItemCount()-1,1,no);
	}
	else
	{
		//断开
		int i;
		int n;
		for(i=0;i<m_ctrlListConnections.GetItemCount();i++)
		{
			n=atoi(m_ctrlListConnections.GetItemText(i,1));
			if(n==No)
			{
				break;
			}
		}
		m_ctrlListConnections.DeleteItem(i);
	}

	m_nCurrentSelect=-1;
}

void CTCPNetKitDlg::OnClickListConnections(NMHDR* pNMHDR, LRESULT* pResult) 
{
	// TODO: Add your control notification handler code here
	m_nCurrentSelect=m_ctrlListConnections.GetSelectionMark();
	
	*pResult = 0;
}

void CTCPNetKitDlg::OnServerDisconnect() 
{
	if(m_nCurrentSelect==-1)
	{
		AfxMessageBox("请先在列表中选择需要断开的连接!");
		return;
	}

	int n;
	n=atoi(m_ctrlListConnections.GetItemText(m_nCurrentSelect,1));

	//断开
	m_psockServer->Disconnect(n);

	CString Status;
	Status=m_ctrlListConnections.GetItemText(m_nCurrentSelect,0)+"手工断开!"+"\r\n";

	//更新列表
	m_ctrlListConnections.DeleteItem(m_nCurrentSelect);
	m_nCurrentSelect=-1;

	//更新显示
	AddMessage(Status,0);
}

void CTCPNetKitDlg::OnServerSend() 
{
	if(m_nCurrentSelect==-1)
	{
		AfxMessageBox("请先在列表中选择需要发送数据的连接!");
		return;
	}

	int n;
	CString Ip,msg;
	Ip=m_ctrlListConnections.GetItemText(m_nCurrentSelect,0);
	n=atoi(m_ctrlListConnections.GetItemText(m_nCurrentSelect,1));

	//发送数据
	
	CString senddata;
	GetDlgItemText(IDC_EDIT_SERVER_SEND,senddata);
	int nRet=m_psockServer->SendServer(n,senddata.GetBuffer(0),senddata.GetLength());

	//更新显示
	if(nRet>0)
	{
		msg="向"+Ip+"发送:"+senddata.Left(nRet)+"\r\n";
		AddMessage(msg,0);
	}

}

void CTCPNetKitDlg::OnClearServerSend() 
{
	SetDlgItemText(IDC_EDIT_SERVER_SEND,"");
}

⌨️ 快捷键说明

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