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

📄 eth_tooldlg.cpp

📁 我自己工程中用来与我的工控板测试udp通信的程序
💻 CPP
字号:
// eth_toolDlg.cpp : 实现文件
//

#include "stdafx.h"
#include "eth_tool.h"
#include "eth_toolDlg.h"
#include "str2hex.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

const int SOCK_TCP	= TRUE;
const int SOCK_UDP  = FALSE;
const int TIMER_PERIODSEND = 1;

BOOL g_bReceiveHex = TRUE;

// 用于应用程序“关于”菜单项的 CAboutDlg 对话框

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// 对话框数据
	enum { IDD = IDD_ABOUTBOX };

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV 支持

// 实现
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()


// Ceth_toolDlg 对话框


Ceth_toolDlg::Ceth_toolDlg(CWnd* pParent /*=NULL*/)
	: CDialog(Ceth_toolDlg::IDD, pParent)
	, m_strServerIP(_T("192.168.0.174"))
	, m_nServerPort(1025)
	, m_bAutoSend(FALSE)
	, m_nPeriod(1000)
	, m_bSendHex(TRUE)
	, m_bReceiveHex(TRUE)
	, m_bSocketType(FALSE)
	, m_strSend(_T(""))
	, m_strReceive(_T(""))
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void Ceth_toolDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	DDX_Text(pDX, IDC_EDIT_SERVER_IP, m_strServerIP);
	DDV_MaxChars(pDX, m_strServerIP, 15);
	DDX_Text(pDX, IDC_EDIT_SERVER_PORT, m_nServerPort);
	DDV_MinMaxUInt(pDX, m_nServerPort, 0, 65535);
	DDX_Check(pDX, IDC_CHECK_AUTO_SEND, m_bAutoSend);
	DDX_Text(pDX, IDC_EDIT_SEND_PERIOD, m_nPeriod);
	DDV_MinMaxUInt(pDX, m_nPeriod, 0, 4294967295);
	DDX_Check(pDX, IDC_CHECK_SEND_HEX, m_bSendHex);
	DDX_Check(pDX, IDC_CHECK_RECEIVE_HEX, m_bReceiveHex);
	DDX_Radio(pDX, IDC_RADIO_UDP, m_bSocketType);
	DDX_Text(pDX, IDC_EDIT_TX, m_strSend);
	DDX_Text(pDX, IDC_EDIT_RX, m_strReceive);
	DDX_Control(pDX, IDC_BUTTON_CONNECT, m_btnConnect);
	DDX_Control(pDX, IDC_EDIT_RX, m_edtReceive);
}

BEGIN_MESSAGE_MAP(Ceth_toolDlg, CDialog)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	//}}AFX_MSG_MAP
	ON_BN_CLICKED(IDC_BUTTON_CLEAR_TX, &Ceth_toolDlg::OnBnClickedButtonClearTx)
	ON_BN_CLICKED(IDC_BUTTON_SEND, &Ceth_toolDlg::OnBnClickedButtonSend)
	ON_BN_CLICKED(IDC_BUTTON_CLEAR_RX, &Ceth_toolDlg::OnBnClickedButtonClearRx)
	ON_BN_CLICKED(IDC_BUTTON_SAVE, &Ceth_toolDlg::OnBnClickedButtonSave)
	ON_BN_CLICKED(IDC_BUTTON_CONNECT, &Ceth_toolDlg::OnBnClickedButtonConnect)
	ON_WM_DESTROY()
	ON_BN_CLICKED(IDC_CHECK_SEND_HEX, &Ceth_toolDlg::OnBnClickedCheckSendHex)
	ON_WM_TIMER()
	ON_BN_CLICKED(IDC_CHECK_AUTO_SEND, &Ceth_toolDlg::OnBnClickedCheckAutoSend)
END_MESSAGE_MAP()


// Ceth_toolDlg 消息处理程序

BOOL Ceth_toolDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// 将“关于...”菜单项添加到系统菜单中。

	// IDM_ABOUTBOX 必须在系统命令范围内。
	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);
		}
	}

	// 设置此对话框的图标。当应用程序主窗口不是对话框时,框架将自动
	//  执行此操作
	SetIcon(m_hIcon, TRUE);			// 设置大图标
	SetIcon(m_hIcon, FALSE);		// 设置小图标

	// TODO: 在此添加额外的初始化代码
	UpdateData(TRUE);

	CString strLocal;
	m_SocketManager.GetLocalAddress( strLocal.GetBuffer(256), 256);
	strLocal.ReleaseBuffer();
	//m_strServerIP=strLocal;

	// Initialize socket manager
	m_SocketManager.SetMessageWindow( &m_edtReceive );
	m_SocketManager.SetServerState( false );	// run as client
	m_SocketManager.SetSmartAddressing( false );	// always send to server
	g_bReceiveHex=m_bReceiveHex;

	UpdateData(FALSE);

	return TRUE;  // 除非将焦点设置到控件,否则返回 TRUE
}

void Ceth_toolDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// 如果向对话框添加最小化按钮,则需要下面的代码
//  来绘制该图标。对于使用文档/视图模型的 MFC 应用程序,
//  这将由框架自动完成。

void Ceth_toolDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // 用于绘制的设备上下文

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// 使图标在工作矩形中居中
		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;

		// 绘制图标
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

//当用户拖动最小化窗口时系统调用此函数取得光标显示。
//
HCURSOR Ceth_toolDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}

BOOL Ceth_toolDlg::PreTranslateMessage(MSG* pMsg)
{
	// TODO: 在此添加专用代码和/或调用基类
	if (pMsg->message == WM_KEYDOWN)
	{
		int nVirtKey = (int) pMsg->wParam;
		if (nVirtKey == VK_ESCAPE)
			return TRUE;

		if (nVirtKey == VK_RETURN && (GetFocus()->m_hWnd  == GetDlgItem(IDC_EDIT_TX)->GetSafeHwnd()))
		{
			if (m_SocketManager.IsOpen())
				OnBnClickedButtonSend();
			return TRUE;
		}
	}

	return CDialog::PreTranslateMessage(pMsg);
}

void Ceth_toolDlg::OnBnClickedButtonClearTx()
{
	// TODO: 在此添加控件通知处理程序代码
	UpdateData(TRUE);
	m_strSend.Empty();
	UpdateData(FALSE);
}

void Ceth_toolDlg::OnBnClickedButtonSend()
{
	// TODO: 在此添加控件通知处理程序代码
	UpdateData(TRUE);
	g_bReceiveHex=m_bReceiveHex;
	
	if(m_strSend.IsEmpty())
		return ;
	
	if(!m_SocketManager.IsOpen())
		OnBnClickedButtonConnect();
	
	BYTE *byteBuffer;
	CString strText;
	
	// Update so that we can retrieve new port number also... :-)
	if(m_bSendHex)
	{
		m_strSend=FilterHexStr(m_strSend);
		UpdateData(FALSE);
		
		strText=m_strSend;
		byteBuffer=new BYTE[strText.GetLength()/2+1];
		HexStr2IntArray(strText,byteBuffer);
		
		USES_CONVERSION;
		m_SocketManager.WriteComm( byteBuffer, strText.GetLength()/2, INFINITE);
		
		delete[] byteBuffer;
	}
	else
	{
		strText=m_strSend;		
		int nLen = strText.GetLength();		
		if (nLen > 0)
		{
			strText += _T("\r\n");
			nLen = strText.GetLength() + 1;
			USES_CONVERSION;
			
			byteBuffer=new BYTE[nLen];
			strcpy_s((LPSTR)byteBuffer, nLen, T2CA(strText));

			m_SocketManager.WriteComm( byteBuffer, nLen, INFINITE);

			delete[] byteBuffer;
		}
	}
}

void Ceth_toolDlg::OnBnClickedButtonClearRx()
{
	// TODO: 在此添加控件通知处理程序代码
	UpdateData(true);
	m_strReceive.Empty();
	UpdateData(false);
}

void Ceth_toolDlg::OnBnClickedButtonSave()
{
	// TODO: 在此添加控件通知处理程序代码
	CString strPath;
	
	UpdateData(TRUE);
	
	CString strFile;	
	CFileDialog fd(false,_T("txt"),strFile,OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,_T("文本文件(*.txt)|*.txt|所有文件(*.*)|*.*||"),NULL);
	if(fd.DoModal()==IDOK) // 获得文件路径
		strFile=fd.GetPathName();
	else
		return ;

	strPath=strFile.Left(strFile.ReverseFind(_T('\\'))+1);
	
	CFile file;
	if(!file.Open(strFile, CFile::modeCreate|CFile::modeReadWrite))
	{
		MessageBox(_T("文件创建失败!"),strFile);
		return ;
	}
	
	file.Write(m_strReceive,m_strReceive.GetLength());
	file.Flush();
	
	file.Close();
}

void Ceth_toolDlg::OnBnClickedButtonConnect()
{
	// TODO: 在此添加控件通知处理程序代码
	CString strConnect;
	m_btnConnect.GetWindowText(strConnect);

	Sleep(10); // wait connect/disconnect complete
	if(strConnect==_T("连接"))
	{
		Connect();
	}
	else if(strConnect==_T("断开"))
	{
		Disconnect();
	}
}

void Ceth_toolDlg::Connect(void) 
{
	UpdateData(TRUE);

	CString strServer=m_strServerIP;
	CString strPort;
	bool bSuccess=FALSE;

	strPort.Format(_T("%d"),m_nServerPort);
	if (m_bSocketType == SOCK_TCP)
	{
		bSuccess = m_SocketManager.ConnectTo( strServer, strPort, AF_INET, SOCK_STREAM); // TCP
	}
	else
	{
		bSuccess = m_SocketManager.ConnectTo( strServer, strPort, AF_INET, SOCK_DGRAM); // UDP
	}

	if (bSuccess && m_SocketManager.WatchComm())
	{
		//GetDlgItem(IDC_BTN_SEND)->EnableWindow( TRUE );
		//GetDlgItem(IDC_BTN_STOP)->EnableWindow( TRUE );
		//NextDlgCtrl();
		//GetDlgItem(IDC_BTN_START)->EnableWindow( FALSE );
		//GetDlgItem(IDC_TCP)->EnableWindow( FALSE );
		//GetDlgItem(IDC_UDP)->EnableWindow( FALSE );
		CString strMsg;
		
		if (m_bSocketType == SOCK_TCP)
		{
			strMsg = _T("Connection established with server: ") + strServer;
			strMsg += _T(" on port ") + strPort + CString(_T("\r\n"));
			m_SocketManager.GetPeerName( m_SockPeer );
		}
		else
		{
			SockAddrIn addrin;
			m_SocketManager.GetSockName( addrin );	// just to get our current address
			LONG  uAddr = addrin.GetIPAddr();
			BYTE* sAddr = (BYTE*) &uAddr;
			short nPort = ntohs( addrin.GetPort() );
			CString strAddr;
			// Address is stored in network format...
			strAddr.Format(_T("IP: %u.%u.%u.%u, Port: %d"),
				(UINT)(sAddr[0]), (UINT)(sAddr[1]),
				(UINT)(sAddr[2]), (UINT)(sAddr[3]), nPort);
			strMsg = _T("Socket created: ") + strAddr + CString(_T("\r\n"));
			m_SockPeer.CreateFrom( strServer, strPort, AF_INET);
		}
		
		m_btnConnect.SetWindowText(_T("断开"));
		
		m_strReceive=strMsg;
		UpdateData(FALSE);
	}
}

void Ceth_toolDlg::Disconnect(void) 
{
	// Disconnect socket
	m_SocketManager.StopComm();
	if (!m_SocketManager.IsOpen())
	{
		//GetDlgItem(IDC_BTN_START)->EnableWindow( TRUE );
		//PrevDlgCtrl();
		//GetDlgItem(IDC_BTN_SEND)->EnableWindow( FALSE );
		//GetDlgItem(IDC_BTN_STOP)->EnableWindow( FALSE );
		//GetDlgItem(IDC_TCP)->EnableWindow( TRUE );
		//GetDlgItem(IDC_UDP)->EnableWindow( TRUE );

		m_btnConnect.SetWindowText(_T("连接"));
	}
}


void Ceth_toolDlg::OnDestroy()
{
	if(m_SocketManager.IsOpen())
		m_SocketManager.StopComm();

	CDialog::OnDestroy();

	// TODO: 在此处添加消息处理程序代码
}

void Ceth_toolDlg::OnBnClickedCheckSendHex()
{
	// TODO: Add your control notification handler code here
	UpdateData(TRUE);
	
	g_bReceiveHex=m_bReceiveHex;
}

void Ceth_toolDlg::OnTimer(UINT_PTR nIDEvent)
{
	// TODO: Add your message handler code here and/or call default
	UpdateData(TRUE);
	if(m_strReceive.GetLength() > 1024*1024) // 1M Bytes
	{
		m_strReceive.Empty();
		UpdateData(FALSE);
	}

	OnBnClickedButtonSend();

	CDialog::OnTimer(nIDEvent);
}

void Ceth_toolDlg::OnBnClickedCheckAutoSend()
{
	// TODO: Add your control notification handler code here
	UpdateData(TRUE);

	if(m_bAutoSend)
		SetTimer(TIMER_PERIODSEND, m_nPeriod,NULL);
	else
		KillTimer(TIMER_PERIODSEND);
}

⌨️ 快捷键说明

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