TCP通信C++实现案例
https://www.bilibili.com/video/BV1Dt411p74c?t=1746
== 全部来自以上视频,纯属搬运,小可爱有问题可以举手提问哈。==
服务器端
Server头文件
#pragma once
#define WM_SOCKET WM_USER+1000
class CServerDlg : public CDialogEx
{
public:
CServerDlg(CWnd* pParent = nullptr);
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_SERVER_DIALOG };
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX);
protected:
HICON m_hIcon;
virtual BOOL OnInitDialog();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg LRESULT OnSocket(WPARAM wParam,LPARAM lParma);
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
DECLARE_MESSAGE_MAP()
public:
SOCKET s;
SOCKET s1;
int n=0;
sockaddr_in addr;
sockaddr_in addr1;
public:
afx_msg void OnBnClickedSend();
};
ServerDlg.cpp
#include "pch.h"
#include "framework.h"
#include "Server.h"
#include "ServerDlg.h"
#include "afxdialogex.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
class CAboutDlg : public CDialogEx
{
public:
CAboutDlg();
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_ABOUTBOX };
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX);
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()
CServerDlg::
CServerDlg(CWnd* pParent )
: CDialogEx(IDD_SERVER_DIALOG, pParent)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CServerDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CServerDlg, CDialogEx)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_MESSAGE(WM_SOCKET, &CServerDlg::OnSocket)
ON_BN_CLICKED(IDC_SEND, &CServerDlg::OnBnClickedSend)
END_MESSAGE_MAP()
BOOL CServerDlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != nullptr)
{
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);
}
}
SetIcon(m_hIcon, TRUE);
SetIcon(m_hIcon, FALSE);
s = socket(AF_INET, SOCK_STREAM, 0);
addr.sin_family = AF_INET;
addr.sin_port = htons(8000);
addr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
bind(s, (sockaddr*)&addr,sizeof(addr));
listen(s, 5);
WSAAsyncSelect(s, this->m_hWnd, WM_SOCKET, FD_ACCEPT | FD_READ);
GetDlgItem(IDC_ADDR)->SetWindowTextA("服务器监听已经启动!");
GetDlgItem(IDC_TEXT)->EnableWindow(false);
return TRUE;
}
void CServerDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialogEx::OnSysCommand(nID, lParam);
}
}
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
{
CDialogEx::OnPaint();
}
}
HCURSOR CServerDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
afx_msg LRESULT CServerDlg::OnSocket(WPARAM wParam, LPARAM lParam)
{
CString str;
char cs[100] = "";
switch (lParam)
{
case FD_ACCEPT:
{
int lengther = sizeof(addr1);
s1 = accept(s, (sockaddr*)&addr1, &lengther);
n = n + 1;
str.Format("有 %d 个客户端已经连接上了服务器", n);
str += inet_ntoa(addr1.sin_addr);
str += "\r\n登陆\r\n";
GetDlgItem(IDC_TEXT)->SetWindowTextA(str);
} break;
case FD_READ:
{
CString num = "";
recv(s1, cs, 100, 0);
GetDlgItem(IDC_TEXT)->GetWindowTextA(num);
num += "\r\n";
num += "客户端:";
num += (LPTSTR)cs;
GetDlgItem(IDC_TEXT)->SetWindowTextA(num);
}break;
default:
break;
}
return 0;
}
void CServerDlg::OnBnClickedSend()
{
CString str = "";
GetDlgItem(IDC_SENDTEXT)->GetWindowTextA(str);
if (str == "")
{
MessageBox("消息不能为空!");
}
else {
if (send(s1, str.GetBuffer(1), str.GetLength(), 0) != SOCKET_ERROR) {
GetDlgItem(IDC_TEXT)->GetWindowTextA(str);
str += "消息已经发送到客户端。\r\n";
GetDlgItem(IDC_TEXT)->SetWindowTextA(str);
}
else {
GetDlgItem(IDC_TEXT)->SetWindowTextA("消息发送失败。\r\n");
}
}
}
客户端
顺便加了一个断开连接的按钮,可做可不做哈。
Client头文件
#pragma once
#define WM_SOCKET WM_USER+1000
class CClientDlg : public CDialogEx
{
public:
CClientDlg(CWnd* pParent = nullptr);
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_CLIENT_DIALOG };
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX);
protected:
HICON m_hIcon;
virtual BOOL OnInitDialog();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnPaint();
afx_msg LRESULT OnSocket(WPARAM wParam, LPARAM lParam);
afx_msg HCURSOR OnQueryDragIcon();
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnBnClickedConnect();
afx_msg void OnBnClickedSend();
SOCKET s;
sockaddr_in addr;
afx_msg void OnBnClickedDisconnect();
};
ClientDlg.cpp
#include "pch.h"
#include "framework.h"
#include "Client.h"
#include "ClientDlg.h"
#include "afxdialogex.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
class CAboutDlg : public CDialogEx
{
public:
CAboutDlg();
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_ABOUTBOX };
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX);
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()
CClientDlg::CClientDlg(CWnd* pParent )
: CDialogEx(IDD_CLIENT_DIALOG, pParent)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CClientDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CClientDlg, CDialogEx)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_CONNECT, &CClientDlg::OnBnClickedConnect)
ON_BN_CLICKED(IDC_SEND, &CClientDlg::OnBnClickedSend)
ON_MESSAGE(WM_SOCKET, &CClientDlg::OnSocket)
ON_BN_CLICKED(IDC_DISCONNECT, &CClientDlg::OnBnClickedDisconnect)
END_MESSAGE_MAP()
BOOL CClientDlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != nullptr)
{
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);
}
}
SetIcon(m_hIcon, TRUE);
SetIcon(m_hIcon, FALSE);
GetDlgItem(IDC_SEND)->EnableWindow(FALSE);
GetDlgItem(IDC_TEXT)->EnableWindow(FALSE);
GetDlgItem(IDC_SENDTEXT)->EnableWindow(FALSE);
s = socket(AF_INET, SOCK_STREAM, 0);
WSAAsyncSelect(s, this->m_hWnd, WM_SOCKET,FD_READ);
return TRUE;
}
void CClientDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialogEx::OnSysCommand(nID, lParam);
}
}
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
{
CDialogEx::OnPaint();
}
}
HCURSOR CClientDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
void CClientDlg::OnBnClickedConnect()
{
CString str, str1;
int port;
GetDlgItem(IDC_ADDR)->GetWindowTextA(str);
GetDlgItem(IDC_PORT)->GetWindowTextA(str1);
if (str == "" | str1 == "")
{
MessageBox("端口或者服务器地址不能为空。");
}
else
{
port = atoi(str1.GetBuffer(1));
addr.sin_family = AF_INET;
addr.sin_port = ntohs(port);
addr.sin_addr.S_un.S_addr = inet_addr(str.GetBuffer(1));
GetDlgItem(IDC_TEXT)->SetWindowTextA("正在连接服务器。。。\r\n");
if (connect(s, (sockaddr*)&addr, sizeof(addr)))
{
GetDlgItem(IDC_TEXT)->GetWindowTextA(str);
str += "连接服务器成功。\r\n";
GetDlgItem(IDC_TEXT)->SetWindowTextA(str);
GetDlgItem(IDC_SENDTEXT)->EnableWindow(true);
GetDlgItem(IDC_SEND)->EnableWindow(true);
GetDlgItem(IDC_ADDR)->EnableWindow(false);
GetDlgItem(IDC_PORT)->EnableWindow(false);
GetDlgItem(IDC_CONNECT)->EnableWindow(false);
}
else {
GetDlgItem(IDC_TEXT)->GetWindowTextA(str);
str += "连接服务器失败。\r\n";
GetDlgItem(IDC_TEXT)->SetWindowTextA(str);
}
}
}
void CClientDlg::OnBnClickedSend()
{
CString str, str1;
GetDlgItem(IDC_SENDTEXT)->GetWindowTextA(str);
if (str == "") {
MessageBox("消息不能发送为空。");
}
else {
send(s, str.GetBuffer(1), str.GetLength(), 0);
GetDlgItem(IDC_TEXT)->GetWindowTextA(str1);
str1 = "\r\n";
str1 += str;
GetDlgItem(IDC_TEXT)->SetWindowTextA(str1);
}
}
afx_msg LRESULT CClientDlg::OnSocket(WPARAM wParam, LPARAM lParam)
{
char cs[100] = "";
if (lParam == FD_READ)
{
CString num = "";
recv(s, cs, 100, 0);
GetDlgItem(IDC_TEXT)->GetWindowTextA(num);
num += "\r\n服务器";
num += (LPTSTR)cs;
GetDlgItem(IDC_TEXT)->SetWindowTextA(num);
}
return 0;
}
void CClientDlg::OnBnClickedDisconnect()
{
closesocket(s);
GetDlgItem(IDC_SENDTEXT)->EnableWindow(false);
GetDlgItem(IDC_SEND)->EnableWindow(false);
GetDlgItem(IDC_ADDR)->EnableWindow(true);
GetDlgItem(IDC_PORT)->EnableWindow(true);
GetDlgItem(IDC_CONNECT)->EnableWindow(true);
}
运行截图:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)