首页 > 代码库 > Socket 学习之 MFC:简单通信

Socket 学习之 MFC:简单通信

最终界面如图所示:

客户端代码如下:

// ClientDlg.h : 头文件
//

#pragma once

UINT Recv_Th(LPVOID p);

// CClientDlg 对话框
class CClientDlg : public CDialog
{
// 构造
public:
	CClientDlg(CWnd* pParent = NULL);	// 标准构造函数

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

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


// 实现
protected:
	HICON m_hIcon;

	// 生成的消息映射函数
	virtual BOOL OnInitDialog();
	afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
	afx_msg void OnPaint();
	afx_msg HCURSOR OnQueryDragIcon();
	DECLARE_MESSAGE_MAP()

public:
	void  Update(CString str);

private:
	CEdit * edit_ip;
	CEdit * edit_send;
	CEdit * edit_show;
	CButton * btn_conn;
public:
	afx_msg void OnBnClickedBsend();
	afx_msg void OnBnClickedBconn();
};
// ClientDlg.cpp : 实现文件
//

#include <winsock2.h>
#include "stdafx.h"
#include "Client.h"
#include "ClientDlg.h"

#pragma comment(lib, "WS2_32.lib")

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

SOCKET sock;

// 用于应用程序“关于”菜单项的 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)
{
	EnableActiveAccessibility();
}

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

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()


// CClientDlg 对话框




CClientDlg::CClientDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CClientDlg::IDD, pParent)
{
	EnableActiveAccessibility();
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

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

BEGIN_MESSAGE_MAP(CClientDlg, CDialog)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	//}}AFX_MSG_MAP
	ON_BN_CLICKED(IDC_BSEND, &CClientDlg::OnBnClickedBsend)
	ON_BN_CLICKED(IDC_BCONN, &CClientDlg::OnBnClickedBconn)
END_MESSAGE_MAP()


// CClientDlg 消息处理程序

BOOL CClientDlg::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);		// 设置小图标

	ShowWindow(SW_MINIMIZE);

	// TODO: 在此添加额外的初始化代码
	 edit_show = (CEdit *)GetDlgItem(IDC_ESHOW);
	 edit_send = (CEdit *)GetDlgItem(IDC_ESEND);
	 btn_conn = (CButton *)GetDlgItem(IDC_BCONN);
	 edit_ip = (CEdit *)GetDlgItem(IDC_EIP);

	 edit_ip->SetWindowText("172.16.70.80");

	 if (!AfxSocketInit())
	 {
		  AfxMessageBox(IDP_SOCKETS_INIT_FAILED);
		  return FALSE;
	 }

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

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

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

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

void CClientDlg::Update(CString str)
{
	edit_show->ReplaceSel(str + "\r\n");
}

UINT Recv_Th(LPVOID p)
{
	 int res;
	 char msg[1024];
	 CString str;
	 CClientDlg * dlg = (CClientDlg *) AfxGetApp()->GetMainWnd();
	 dlg->Update("Initialization");
 
	 while(1)
	 {
		  if( (res = recv(sock, msg, 1024, 0)) == -1)
		  {
			   dlg->Update("失去连接");
			   break;
		  }
		  else
		  {
			   msg[res] = '\0';
			   dlg->Update("server:" + CString(msg));
		  }
	 }
	 return 0;
}
void CClientDlg::OnBnClickedBsend()
{
	// TODO: 在此添加控件通知处理程序代码
	CString str;
	 char * msg;
	 edit_send->GetWindowText(str);
	 msg = str.GetBuffer(str.GetLength());
	 if(send(sock, msg, strlen(msg), 0) == SOCKET_ERROR)
	 {
			Update("发送失败");
	 }
	 else if(str == "")
	 {
			MessageBox("请输入信息");
	 }
	 else
	 {
		  Update("client:" + str);//消息上屏,清空输入,并重获焦点
		  edit_send->SetWindowText("");
		  edit_send->SetFocus();
	 }
}

void CClientDlg::OnBnClickedBconn()
{
	// TODO: 在此添加控件通知处理程序代码
	WSADATA wsaData;
	 SOCKADDR_IN server_addr;

	 WORD wVersion;

	 wVersion = MAKEWORD(2,2);

	 WSAStartup(wVersion,&wsaData);

	 CString ip;
	 edit_ip->GetWindowText(ip);//取得服务器的IP地址
	 server_addr.sin_addr.s_addr = inet_addr(ip);
	 server_addr.sin_family = AF_INET;
	 server_addr.sin_port = htons(5150);
	 if( (sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET)
	 {
		edit_show->ReplaceSel("create socket error\r\n");
	 }
	 if( connect(sock, (struct sockaddr *) &server_addr, sizeof(SOCKADDR_IN)) == SOCKET_ERROR)
	 {
		edit_show->ReplaceSel("连接失败\r\n");
	 }
	 else
	 {
		  edit_show->ReplaceSel("连接成功\r\n");
		  AfxBeginThread(&Recv_Th, 0);
		  btn_conn->EnableWindow(FALSE);//按钮变灰
	 }
}

服务器端代码如下:

// ServerDlg.h : 头文件
//

#pragma once

UINT Server_Th(LPVOID p);

// CServerDlg 对话框
class CServerDlg : public CDialog
{
// 构造
public:
	CServerDlg(CWnd* pParent = NULL);	// 标准构造函数

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

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


// 实现
protected:
	HICON m_hIcon;

	// 生成的消息映射函数
	virtual BOOL OnInitDialog();
	afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
	afx_msg void OnPaint();
	afx_msg HCURSOR OnQueryDragIcon();
	DECLARE_MESSAGE_MAP()

public:
	void  Update(CString str);

private:
	CEdit * show_edit;
	CEdit * send_edit;
public:
	afx_msg void OnBnClickedBsend();
};

// ServerDlg.cpp : 实现文件
//

#include "winsock2.h"
#pragma comment(lib, "WS2_32.lib")

#include "stdafx.h"
#include "Server.h"
#include "ServerDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

SOCKET listen_sock;
SOCKET sock;

// 用于应用程序“关于”菜单项的 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)
{
	EnableActiveAccessibility();
}

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

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()


// CServerDlg 对话框




CServerDlg::CServerDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CServerDlg::IDD, pParent)
{
	EnableActiveAccessibility();
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

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

BEGIN_MESSAGE_MAP(CServerDlg, CDialog)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	//}}AFX_MSG_MAP
	ON_BN_CLICKED(IDC_BSEND, &CServerDlg::OnBnClickedBsend)
END_MESSAGE_MAP()


// CServerDlg 消息处理程序

BOOL CServerDlg::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);		// 设置小图标

	ShowWindow(SW_MINIMIZE);

	// TODO: 在此添加额外的初始化代码
	AfxBeginThread(&Server_Th, 0);

	show_edit = (CEdit *)GetDlgItem(IDC_ESHOW);
	send_edit = (CEdit *)GetDlgItem(IDC_ESEND);

	send_edit->SetFocus();

	 char name[80];
	 CString IP;
	 hostent * pHost;
	 gethostname(name, 128);//获得主机名
	 pHost = gethostbyname(name);//获得主机结构
	 IP = inet_ntoa(*(in_addr *)pHost->h_addr);
	 Update("本机IP地址:" + IP);	 

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

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

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

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

void CServerDlg::Update(CString str)
{
	show_edit->ReplaceSel(str + "\r\n");
}

UINT Server_Th(LPVOID p)
{
	 WSADATA wsaData;

	 WORD wVersion;

	 wVersion = MAKEWORD(2,2);

	 WSAStartup(wVersion,&wsaData);
	
	 SOCKADDR_IN local_addr;
	 SOCKADDR_IN client_addr;
	 int iaddrSize = sizeof(SOCKADDR_IN);
	 int res;
	 char msg[1024];
	 CServerDlg * dlg = (CServerDlg *)AfxGetApp()->GetMainWnd();
	 local_addr.sin_family = AF_INET;
	 local_addr.sin_port = htons(5150);
	 local_addr.sin_addr.s_addr = htonl(INADDR_ANY);
 
	 if( (listen_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET )
	 {
		dlg->Update("创建监听失败");
	 }
	 if( bind(listen_sock, (struct sockaddr*) &local_addr, sizeof(SOCKADDR_IN)) )
	 {
		dlg->Update("绑定错误");
	 }
	listen(listen_sock, 1);
	 if( (sock = accept(listen_sock, (struct sockaddr *)&client_addr, &iaddrSize)) == INVALID_SOCKET)
	 {
		dlg->Update("accept 失败");
	 }
	 else
	 {
		  CString port;
		  port.Format("%d", int(ntohs(client_addr.sin_port)));
		  dlg->Update( "已连接来自:" + CString(inet_ntoa(client_addr.sin_addr)) + "  端口:" +  port);
	 }
 
	 //接收数据
	 while(1)
	 {
		  if( (res = recv(sock, msg, 1024, 0)) == -1 )
		  {
			   dlg->Update("失去连接");
			   break;
		  }
		  else
		  {
			   msg[res] = '\0';
			   dlg->Update("client:" + CString(msg));
		  }
	 }
	return 0;
}
void CServerDlg::OnBnClickedBsend()
{
	// TODO: 在此添加控件通知处理程序代码
	 CString str;
	 char * msg;
	 send_edit->GetWindowText(str);
	 msg = str.GetBuffer(str.GetLength());

	 if(send(sock, msg, strlen(msg), 0) == SOCKET_ERROR)
	 {
		show_edit->ReplaceSel("发送失败\r\n");
	 }

	 else if(str == "")
	 {
		MessageBox("请输入信息");
	 }
	 else
	 {
		  show_edit->ReplaceSel("server:" + str + "\r\n");//消息上屏,清空输入,并重获焦点
		  send_edit->SetWindowText("");
		  send_edit->SetFocus();
	 }
}


Socket 学习之 MFC:简单通信