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

📄 tcpclientdlg.cpp

📁 winsock通讯
💻 CPP
字号:
// TCPClientDlg.cpp : implementation file
//

#include "stdafx.h"
#include "TCPClient.h"
#include "TCPClientDlg.h"

#define SENDMESSAGE WM_USER+1000
#define BUFFERLEN 500

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

/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

int index=0;


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

/////////////////////////////////////////////////////////////////////////////
// CTCPClientDlg dialog

CTCPClientDlg::CTCPClientDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CTCPClientDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CTCPClientDlg)
	m_setIp = _T("");
	m_localName = _T("");
	m_setPort = _T("");
	m_srvReply = _T("");
	m_sendMessage = _T("");
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CTCPClientDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CTCPClientDlg)
	DDX_Control(pDX, IDC_SENDMESSAGE, m_sendMessageCtl);
	DDX_Control(pDX, IDC_INFOLIST, m_infoListCtl);
	DDX_Control(pDX, IDC_IPADDRESS, m_connectIpCtl);
	DDX_Control(pDX, IDC_CONNECTPORT, m_setPortCtl);
	DDX_Text(pDX, IDC_LOCALIP, m_setIp);
	DDX_Text(pDX, IDC_LOACALNAME, m_localName);
	DDX_Text(pDX, IDC_CONNECTPORT, m_setPort);
	DDX_Text(pDX, IDC_REPLY, m_srvReply);
	DDX_Text(pDX, IDC_SENDMESSAGE, m_sendMessage);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CTCPClientDlg, CDialog)
	//{{AFX_MSG_MAP(CTCPClientDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_WM_RBUTTONDOWN()
	ON_COMMAND(IDM_CONNECTSRV, OnConnectsrv)
	ON_BN_CLICKED(IDC_BTNSENDMESSAGE, OnBtnsendmessage)
	//}}AFX_MSG_MAP
	ON_MESSAGE(SENDMESSAGE,SendData)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CTCPClientDlg message handlers

BOOL CTCPClientDlg::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
	   char hostname[256]={0};
	   LPCSTR IPAddress;
	   struct hostent * pHost; //定义结构体 hostent
	   
	   if(gethostname(hostname,sizeof(hostname))==0)
	   {
		   m_localName=hostname;
	   }
	   pHost=gethostbyname(hostname);
	   
	   for(int i=0;pHost!=NULL&&pHost->h_addr_list[i]!=NULL;i++) 
	   {
		   IPAddress=inet_ntoa (*(struct in_addr *)pHost->h_addr_list[i]);      
	   }
        m_setIp=IPAddress;

		m_client=socket(AF_INET,SOCK_STREAM,0);
//		WSAAsyncSelect(m_client,m_hWnd,SENDMESSAGE,FD_WRITE|FD_READ|FD_CLOSE);
		UpdateData(false);
	
	return TRUE;  // return TRUE  unless you set the focus to a control
}

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

void CTCPClientDlg::OnRButtonDown(UINT nFlags, CPoint point) 
{
	// TODO: Add your message handler code here and/or call default
	CMenu menu;
	menu.LoadMenu(IDR_MENU1);
   CMenu *Popup = menu.GetSubMenu(0);

    CPoint m_point;
	GetCursorPos(&m_point);
	SetForegroundWindow();
	Popup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON,m_point.x,m_point.y,this);
	CDialog::OnRButtonDown(nFlags, point);
}

BOOL CTCPClientDlg::OnConnectsrv() 
{
	UpdateData();
	if(m_setPort.IsEmpty())
	{
		AfxMessageBox("请输入端口地址");
		return 0;
	}
	
	if(m_connectIpCtl.IsBlank())
	{
		AfxMessageBox("请输入IP地址");
		return 0 ;
	}
	CString info1,info2,info3; 
	info1.Format("客户端正在进入服务器>>>>请稍后......");
	info2.Format("客户端无法进入服务器>>>>");
	info3.Format("客户端已经进入服务器>>>>");
	
	m_infoListCtl.InsertString(index,info1);
	index++;
	
	m_connectIpCtl.GetAddress(dwIP);
	int port=atoi(m_setPort);
	
	sockaddr_in clientaddr;
	clientaddr.sin_family=AF_INET;

 
	clientaddr.sin_port=htons(port);
	clientaddr.sin_addr.S_un.S_addr=htonl(dwIP);
 //    clientaddr.sin_port=htons(1500);
 //   clientaddr.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");
	if(SOCKET_ERROR==connect(m_client,(sockaddr*)&clientaddr,sizeof(clientaddr)))
	{
	   
		m_infoListCtl.InsertString(index,info2);
		index++;

	}
	else
	{
		m_infoListCtl.InsertString(index,info3);
		index++;
	}
    WSAAsyncSelect(m_client,m_hWnd,SENDMESSAGE,FD_WRITE|FD_READ|FD_CLOSE);
	return 0;
	// TODO: Add your command handler code here
	
}

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

void CTCPClientDlg::SendData(UINT wParam,LONG lParam)
{
	char szReceive[BUFFERLEN]={0};
	char szSend[BUFFERLEN]={0};
	CString  info;
  
	m_sendSrvMessage=(SOCKET)wParam;
	UpdateData();
	switch(LOWORD(lParam))
	{
	case FD_WRITE:
		{
			if(m_sendMessage.IsEmpty())
			{
				if(IDOK==AfxMessageBox("确定要发送空消息!",MB_OKCANCEL))
				{
					info.Format("客户端说:     ");				  
					send(SOCKET(wParam),info.GetBuffer(0),info.GetLength(),0);
					m_infoListCtl.InsertString(index,info);
					index++;
				} 
				else
				{
					m_sendMessage=" ";
					UpdateData(FALSE);
					m_sendMessageCtl.SetFocus();
				}
			}
			else
			{
				info.Format("客户端端说:%s",m_sendMessage);				  
				send(SOCKET(wParam),info.GetBuffer(0),info.GetLength(),0);
				m_infoListCtl.InsertString(index,info);
				index++;
				m_sendMessageCtl.SetWindowText(" ");
				m_sendMessageCtl.SetFocus();
				
			}
			break;
			
		}
	case FD_READ:
		{
			int receivelen=recv(SOCKET(wParam),szReceive,50,0);
			if(receivelen>0)
			{
				info.Format("%s",szReceive);
				m_srvReply=info;
				m_infoListCtl.InsertString(index,info);
				index++;
				
			}
			else
			{
				if(receivelen=0)
				{
					info.Format("%s","服务端返回消息为空!");
					m_srvReply=info;
					m_infoListCtl.InsertString(index,info);
					index++;
				}
				else
				{
					info.Format("%s","服务端无返回消息!");
					m_srvReply=info;
					m_infoListCtl.InsertString(index,info);
					index++;
				}
				
			}
			UpdateData(false);
			break;
		}
	case FD_CLOSE:
		{
		    info.Format("%s","客户端结束!");
			m_infoListCtl.InsertString(index,info);
			index++;
			shutdown(SOCKET(wParam),2);	
			break;
		}
		
	}
}

void CTCPClientDlg::OnBtnsendmessage() 
{
	// TODO: Add your control notification handler code here
	PostMessage(SENDMESSAGE,m_sendSrvMessage,FD_WRITE);
	
}

⌨️ 快捷键说明

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