Table of Contents
新建项目
MFC Application->Dialog Based(基于对话框的)exe项目Chat
将自带的文本控件与按钮控件删除。添加如下控件。
UI设置
将发送按钮设置为默认,用户按Enter即可发送消息
设置字体为微软雅黑,可以显示中文
项目Project设置
套接字库加载和版本协商version2.2
#include <WinSock2.h>
添加依赖库,如下图
2.在项目属性里设置,告诉编译器,我就用旧版函数,让它不要报错了.
VS2013:
Project properties -> Configuration Properties -> C/C++ -> General -> SDL checks -> No
代码
Chat.cpp
// Chat.cpp : Defines the class behaviors for the application.
//
#include "stdafx.h"
#include "Chat.h"
#include "ChatDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CChatApp
BEGIN_MESSAGE_MAP(CChatApp, CWinApp)
ON_COMMAND(ID_HELP, &CWinApp::OnHelp)
END_MESSAGE_MAP()
// CChatApp construction
CChatApp::CChatApp()
{
// support Restart Manager
m_dwRestartManagerSupportFlags = AFX_RESTART_MANAGER_SUPPORT_RESTART;
// TODO: add construction code here,
// Place all significant initialization in InitInstance
}
CChatApp::~CChatApp()
{
WSACleanup();
}
// The one and only CChatApp object
CChatApp theApp;
// CChatApp initialization
BOOL CChatApp::InitInstance()
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD(2, 2);
//Winsock version 2.2
err = WSAStartup(wVersionRequested, &wsaData);
if (err != 0) {
return FALSE;
}
if (LOBYTE(wsaData.wVersion) != 2 ||
HIBYTE(wsaData.wVersion) != 2) {
WSACleanup();
return FALSE;
}
// InitCommonControlsEx() is required on Windows XP if an application
// manifest specifies use of ComCtl32.dll version 6 or later to enable
// visual styles. Otherwise, any window creation will fail.
INITCOMMONCONTROLSEX InitCtrls;
InitCtrls.dwSize = sizeof(InitCtrls);
// Set this to include all the common control classes you want to use
// in your application.
InitCtrls.dwICC = ICC_WIN95_CLASSES;
InitCommonControlsEx(&InitCtrls);
CWinApp::InitInstance();
AfxEnableControlContainer();
// Create the shell manager, in case the dialog contains
// any shell tree view or shell list view controls.
CShellManager *pShellManager = new CShellManager;
// Activate "Windows Native" visual manager for enabling themes in MFC controls
CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows));
// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need
// Change the registry key under which our settings are stored
// TODO: You should modify this string to be something appropriate
// such as the name of your company or organization
SetRegistryKey(_T("Local AppWizard-Generated Applications"));
CChatDlg dlg;
m_pMainWnd = &dlg;
INT_PTR nResponse = dlg.DoModal();
if (nResponse == IDOK)
{
// TODO: Place code here to handle when the dialog is
// dismissed with OK
}
else if (nResponse == IDCANCEL)
{
// TODO: Place code here to handle when the dialog is
// dismissed with Cancel
}
else if (nResponse == -1)
{
TRACE(traceAppMsg, 0, "Warning: dialog creation failed, so application is terminating unexpectedly.\n");
TRACE(traceAppMsg, 0, "Warning: if you are using MFC controls on the dialog, you cannot #define _AFX_NO_MFC_CONTROLS_IN_DIALOGS.\n");
}
// Delete the shell manager created above.
if (pShellManager != NULL)
{
delete pShellManager;
}
// Since the dialog has been closed, return FALSE so that we exit the
// application, rather than start the application's message pump.
return FALSE;
}
ChatDlg.h : header file
// ChatDlg.h : header file
//
#pragma once
// CChatDlg dialog
#define UM_SOCK WM_USER+1
class CChatDlg : public CDialogEx
{
// Construction
public:
CChatDlg(CWnd* pParent = NULL); // standard constructor
~CChatDlg(); // standard constructor
// Dialog Data
enum { IDD = IDD_CHAT_DIALOG };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
protected:
HICON m_hIcon;
// Generated message map functions
virtual BOOL OnInitDialog();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
afx_msg LRESULT OnSock(WPARAM, LPARAM);
DECLARE_MESSAGE_MAP()
private:
SOCKET m_socket;
public:
bool InitSocket();
afx_msg void OnBnClickedBtnSend();
};
ChatDlg.cpp
// ChatDlg.cpp : implementation file
//
#include "stdafx.h"
#include "Chat.h"
#include "ChatDlg.h"
#include "afxdialogex.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialogEx
{
public:
CAboutDlg();
// Dialog Data
enum { IDD = IDD_ABOUTBOX };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()
// CChatDlg dialog
CChatDlg::CChatDlg(CWnd* pParent /*=NULL*/)
: CDialogEx(CChatDlg::IDD, pParent)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
m_socket = 0; //initialization
}
CChatDlg::~CChatDlg()
{
if (m_socket)
{
closesocket(m_socket);
}
}
void CChatDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CChatDlg, CDialogEx)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_BTN_SEND, &CChatDlg::OnBnClickedBtnSend)
ON_MESSAGE(UM_SOCK, &CChatDlg::OnSock)
END_MESSAGE_MAP()
// CChatDlg message handlers
BOOL CChatDlg::OnInitDialog()
{
CDialogEx::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)
{
BOOL bNameValid;
CString strAboutMenu;
bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
ASSERT(bNameValid);
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
InitSocket();
return TRUE; // return TRUE unless you set the focus to a control
}
void CChatDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialogEx::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 CChatDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<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
{
CDialogEx::OnPaint();
}
}
// The system calls this function to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CChatDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
bool CChatDlg::InitSocket()
{
m_socket = WSASocket(AF_INET, SOCK_DGRAM, 0, NULL, 0, 0);
if (INVALID_SOCKET == m_socket){
MessageBox(_T("Create socket fail!!!"));
}
SOCKADDR_IN addrSock;
addrSock.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
addrSock.sin_family = AF_INET;
addrSock.sin_port = htons(6000);
if (SOCKET_ERROR == bind(m_socket, (SOCKADDR*)&addrSock, sizeof(SOCKADDR)))
{
//MessageBox("绑定失败!");
//MessageBox(_T("绑定失败!"));
MessageBox(_T("Bind Fail!!!"));
return FALSE;
}
if (SOCKET_ERROR == WSAAsyncSelect(m_socket, m_hWnd, UM_SOCK, FD_READ))
{
//MessageBox("注册网络读取事件失败!");
//MessageBox(_T("注册网络读取事件失败!"));
MessageBox(_T("Register Socket Read Fail!!!"));
return FALSE;
}
return TRUE;
//return false;
}
LRESULT CChatDlg::OnSock(WPARAM wParam, LPARAM lParam)
{
LRESULT lResult = 0;
switch (LOWORD(lParam))
{
case FD_READ:
WSABUF wsabuf;
wsabuf.buf = new char[200];
wsabuf.len = 200;
DWORD dwRead;
DWORD dwFlag = 0;
SOCKADDR_IN addrFrom;
int len = sizeof(SOCKADDR);
CString str;
CString strTemp;
HOSTENT *pHost;
if (SOCKET_ERROR == WSARecvFrom(m_socket, &wsabuf, 1, &dwRead, &dwFlag,
(SOCKADDR*)&addrFrom, &len, NULL, NULL))
{
//MessageBox("接收数据失败!");
//MessageBox(_T("接收数据失败!"));
MessageBox(_T("Receive Data Fail!!!"));
lResult = 1;
return lResult;
}
pHost = gethostbyaddr((char*)&addrFrom.sin_addr.S_un.S_addr, 4, AF_INET);
//str.Format("%s说 :%s",inet_ntoa(addrFrom.sin_addr),wsabuf.buf);
str.Format(_T("%s said:%s"), pHost->h_name, wsabuf.buf);
str += "\r\n";
GetDlgItemText(IDC_EDIT_RECV, strTemp);
str += strTemp;
SetDlgItemText(IDC_EDIT_RECV, str);
break;
}
return lResult;
}
void CChatDlg::OnBnClickedBtnSend()
{
// TODO: Add your control notification handler code here
DWORD dwIP;
CString strSend;
WSABUF wsabuf;
DWORD dwSend;
int len;
CString strHostName;
SOCKADDR_IN addrTo;
HOSTENT* pHost;
if (GetDlgItemText(IDC_EDIT_HOSTNAME, strHostName), strHostName == _T(""))
{
((CIPAddressCtrl*)GetDlgItem(IDC_IPADDRESS1))->GetAddress(dwIP);
addrTo.sin_addr.S_un.S_addr = htonl(dwIP);
}
else
{
pHost = gethostbyname(strHostName);
addrTo.sin_addr.S_un.S_addr = *((DWORD*)pHost->h_addr_list[0]);
}
addrTo.sin_family = AF_INET;
addrTo.sin_port = htons(6000);
GetDlgItemText(IDC_EDIT_SEND, strSend);
len = strSend.GetLength();
USES_CONVERSION;
char* cstr;
char temp[100];
::wsprintfA(temp, "%ls", (LPCTSTR)strSend);
cstr = temp;
wsabuf.buf = cstr;
//Method 1- ascii, sunxin
wsabuf.buf = strSend.GetBuffer(len);
wsabuf.len = len + 1;
SetDlgItemText(IDC_EDIT_SEND, _T(""));
if (SOCKET_ERROR == WSASendTo(m_socket, &wsabuf, 1, &dwSend, 0,
(SOCKADDR*)&addrTo, sizeof(SOCKADDR), NULL, NULL))
{
//MessageBox(_T("发送数据失败!"));
MessageBox(_T("Send Data Fail!!!"));
return;
}
}
TODO:
改为UNICODE编程,支持多种语言
来源: VC++深入详解(孙鑫)笔记