客户端代码实现:(大佬请飘过)
一下三个文件分别对应上一期的三个头文件:
具体代码原理看注释,这里小编为了方便将注释用英文编写,部分采用中文,若有看不懂请在评论区留言或者有道翻译
写码不易,关注收藏一下呗,谢谢各位!!!
第三篇文章(服务端实现)
https://blog.csdn.net/qq_42662283/article/details/106493917
Client_LAN.cpp
// Client.cpp : Defines the class behaviors for the application.
#include "stdafx.h"
#include "Client_LAN.h"
#include "ClientDlg_LAN.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CClientApp
BEGIN_MESSAGE_MAP(CClientApp, CWinApp)
ON_COMMAND(ID_HELP, &CWinApp::OnHelp)
END_MESSAGE_MAP()
// CClientApp construction
CClientApp::CClientApp()
{
// support Restart Manager
m_dwRestartManagerSupportFlags = AFX_RESTART_MANAGER_SUPPORT_RESTART;
// TODO: add construction code here,
// Place all significant initialization in InitInstance
}
// The one and only CClientApp object
CClientApp theApp;
// CClientApp initialization
BOOL CClientApp::InitInstance()
{
// 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;
// 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"));
CClientDlg 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
}
// 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;
}
ClientCon_LAN.cpp
#include "stdafx.h"
#include "ClientCon_LAN.h"
#include "ClientDlg_LAN.h"
#include "FileUtil.h"
#pragma comment(lib,"ws2_32.lib") //Winsock Library
ClientCon::ClientCon(CClientDlg *dlg)
{
m_pClient = dlg;
isFile = false;
isReady = false;
sClient = 1;
}
ClientCon::~ClientCon(void)
{
closesocket(sClient);
WSACleanup();
}
void ClientCon::StartConnect(string sAddress, int iPort, string sUsername)
{
const int REC_BUFERSIZE = 2048;
struct sockaddr_in server;
char *message , server_reply[REC_BUFERSIZE + 1];
int recv_size;
m_pUser = sUsername;
printf("\r\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
{
printf("Failed. Error Code : %d",WSAGetLastError());
return;
}
printf("Initialised.\r\n");
//Create a socket(SOCK_STREAM: connection-oriented)
if((sClient = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
{
printf("Could not create socket : %d" , WSAGetLastError());
}
printf("Socket created.\r\n");
server.sin_addr.s_addr = inet_addr(sAddress.c_str());
server.sin_family = AF_INET;
server.sin_port = htons( iPort );
//Connect to remote server
if (connect(sClient, (struct sockaddr *)&server , sizeof(server)) < 0)
{
puts("connect error");
return;
}
//Receive data from the server
while((recv_size = recv(sClient, server_reply , REC_BUFERSIZE, 0)) != SOCKET_ERROR)
{
//Add a NULL terminating character to make it a proper string before printing
server_reply[recv_size] = '\0';
string sTempMsg1 = string(server_reply);
string sTempMsg = string(server_reply) + "\r\n";
//判断是否包含文件.txt标志
if (!(isFile) && (sTempMsg1.find(".txt") != string::npos))
//if(isFile)
{
isFile = true;
file = fu.createFile(server_reply);//创建文件准备存放数据
if (file != NULL)//成功创建文件
{
bool isOver = false;
int i;
while (true)
{
/*fd_set recvfd;
struct timeval tv = { 3, 0 };
FD_ZERO(&recvfd);
FD_SET(sClient, &recvfd);
//检测有没有数据到达socket,有->接收数据,无->break
int result = select(0, &recvfd, NULL, NULL, &tv);*/
//接收数据
recv_size = recv(sClient, server_reply, 2048, 0);
server_reply[recv_size] = '\0';//添加文件结尾标志
Sleep(500);
//判断是否含有规定的文件结束标志
for (i = 0; i < (recv_size - 4); i++)
{
if (server_reply[i] == 'O' &&
server_reply[i + 1] == 'V' &&
server_reply[i + 2] == 'E' &&
server_reply[i + 3] == 'R' &&
server_reply[i + 4] == '!')
{
isOver = true;
break;
}
}
if (isOver)
{
recv_size = (i == recv_size - 4) ? recv_size : (i - 1);
recv_size = (recv_size < 0) ? 0 : recv_size;
fwrite(server_reply, 1, recv_size, file);
break;
}
else
{
//循环一直写入文件
fwrite(server_reply, 1, recv_size, file);
}
}
fclose(file);
isFile = false;
}
}
else
{
if (sTempMsg1 == "READY!")
{
isReady = true;
}
else if(sTempMsg1.length() != 0)//控制信息不打印
{
m_pClient->ShowServerInfo(sTempMsg);
}
}
}
}
void ClientCon::SendData(string sMessage, bool showName)
{
isReady = false;
if (sMessage.length() > 0)
{
string sTemp = m_pUser + ">>" + sMessage + "\r\n";
if (send(sClient, sTemp.c_str(), sTemp.size(), 0) < 0)
{
puts("Send failed");
return;
}
else
{
sTemp = "您(" + m_pUser + ")>>" + sMessage + "\r\n";
//显示自己发送的消息
m_pClient->ShowServerInfo(sTemp);
}
}
}
void ClientCon::SendFile(FILE* file, CString filename)
{
FileUtil fu;
CString a = CString(".txt");
filename.Append(a);//加上后缀
char *data = fu.CString2Char(filename);
isReady = false;
send(sClient, data, filename.GetLength(), 0);//先发送文件名,让接收端做好接受准备
while (!isReady);
isReady = false;
Sleep(100);
const int SEND_BUFSIZE = 512;
char sendData[SEND_BUFSIZE + 1];
char recData[20] = {'0'};
int nCount;//nCount:实际读取的字符数量
while ((nCount = fread(sendData, 1, SEND_BUFSIZE, file)) > 0)//每次读取512个字符一起发送
{
//sendData[nCount] = '\0';
send(sClient, sendData, nCount, 0);
while (!isReady);//阻塞等待接收方发送确认
isReady = false;
}
Sleep(500);
send(sClient, "OVER!", 5, 0);//发送文件发送完毕标志
fclose(file);
}
ClientDlg_LAN.cpp
// ClientDlg.cpp : implementation file
//
#include "stdafx.h"
#include "ClientDlg_LAN.h"
#include "ClientCon_LAN.h"
#include "FileUtil.h"
#include
using namespace std;
#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()
// CClientDlg dialog
CClientDlg::CClientDlg(CWnd* pParent /*=NULL*/)
: CDialogEx(CClientDlg::IDD, pParent),
m_pClient(NULL)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CClientDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Control(pDX, IDC_EDIT_Message, m_Textbox);
}
BEGIN_MESSAGE_MAP(CClientDlg, CDialogEx)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDOK, &CClientDlg::OnBnClickedOk)
ON_BN_CLICKED(IDC_BT_LogIn, &CClientDlg::OnClickedBtLogin)
ON_BN_CLICKED(IDC_BT_LogOut, &CClientDlg::OnClickedBtLogout)
ON_BN_CLICKED(IDC_BT_Send, &CClientDlg::OnClickedBtSend)
ON_BN_CLICKED(IDC_BT_CLEAR, &CClientDlg::OnClickedBtClear)
ON_BN_CLICKED(IDC_BT_FILE, &CClientDlg::OnClickedBtFile)
END_MESSAGE_MAP()
// CClientDlg message handlers
BOOL CClientDlg::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
return TRUE; // return TRUE unless you set the focus to a control
}
void CClientDlg::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 CClientDlg::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 CClientDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
void CClientDlg::ShowServerInfo(string sValue)
{
CString strLine(sValue.c_str());
// add CR/LF to text
//MessageBox(strLine);
AppendTextToEditCtrl(m_Textbox, strLine);
//DoModal();
//UpdateData(TRUE);
}
void CClientDlg::AppendTextToEditCtrl(CEdit& edit, LPCTSTR pszText)
{
// get the initial text length
//MessageBox(pszText);
int nLength = edit.GetWindowTextLength();
// put the selection at the end of text
edit.SetSel(nLength, nLength);
// replace the selection
edit.ReplaceSel(pszText);
}
UINT __cdecl CClientDlg::StaticThreadFunc(LPVOID pParam)
{
CClientDlg *pYourClass = reinterpret_cast<CClientDlg*>(pParam);
UINT retCode = pYourClass->ThreadFunc();
return retCode;
}
UINT CClientDlg::ThreadFunc()
{
CString IPname;
GetDlgItemText(IDC_EDIT_IP, IPname);
CString portname;
GetDlgItemText(IDC_EDIT_Port, portname);
int iPort = _wtoi( portname.GetString() );
CString username;
GetDlgItemText(IDC_EDIT_Name, username);
m_pClient = new ClientCon(this);
CT2CA CStringToAscii(IPname);
//construct a std::string using the LPCSTR input
std::string IPAddress (CStringToAscii);
CT2CA CStringToAscii2(username);
std::string UserName (CStringToAscii2);
//StartConnect()死循环等待数据,所以只能放在子线程
m_pClient->StartConnect(IPAddress, iPort, UserName);
return 0;
}
void CClientDlg::OnBnClickedOk()
{
OnClickedBtLogin();
}
void CClientDlg::OnClickedBtLogin()
{
//一个客户端可能同时连接不止一个服务器,所以开新的线程处理连接
//cTh = AfxBeginThread(StaticThreadFunc, this);
//m_Thread_handle = cTh->m_hThread;
if (m_pClient == NULL)
{
cTh = AfxBeginThread(StaticThreadFunc, this);
m_Thread_handle = cTh->m_hThread;
}
}
void CClientDlg::OnClickedBtLogout()
{
// TODO: 在此添加控件通知处理程序代码
if (m_pClient != NULL)
{
std::string sResultedString(m_pClient->m_pUser + " is logged out\r\n");
m_pClient->SendData(sResultedString);
//ShowServerInfo(sResultedString);
delete m_pClient;
m_pClient = NULL;
}
else
{
ShowServerInfo("You haven't log in yet.\r\n");
}
}
void CClientDlg::OnClickedBtSend()
{
// TODO: 在此添加控件通知处理程序代码
CString sTextData;
GetDlgItemText(IDC_EDIT_SendText, sTextData);
CT2CA CStringToAscii(sTextData);
// construct a std::string using the LPCSTR input
std::string sResultedString(CStringToAscii);
if (m_pClient != NULL)
{
m_pClient->SendData(sResultedString);
}
else
{
ShowServerInfo("Please log in first.\r\n");
}
CWnd* pWnd = GetDlgItem(IDC_EDIT_SendText);
pWnd->SetWindowText(_T(""));//清空发送区
}
void CClientDlg::OnClickedBtClear()
{
// TODO: 在此添加控件通知处理程序代码
CWnd* pWnd = GetDlgItem(IDC_EDIT_Message);
pWnd->SetWindowText(_T("Welcome to Magic TCP chat room!!!\r\n"));//清空接收区
}
void CClientDlg::OnClickedBtFile()
{
// TODO: 在此添加控件通知处理程序代码
// 设置过滤器
TCHAR szFilter[] = _T("记事本文件(*.txt*)|*.txt*|所有文件(*.*)|*.*||");
// 构造打开文件对话框
CFileDialog fileDlg(TRUE, _T("."), NULL, 0, szFilter, this);
CString strFilePath;
CString strFileName;
// 显示打开文件对话框
if (IDOK == fileDlg.DoModal())
{
// 如果点击了文件对话框上的“打开”按钮,则将选择的文件路径显示到编辑框里
strFilePath = fileDlg.GetPathName();
strFileName = fileDlg.GetFileTitle();
FileUtil fu;
FILE *f = fu.openFile(strFilePath);
if ((f != NULL) && (m_pClient != NULL))
{
m_pClient->SendData("群发了文件" + std::string(CW2A(strFileName.GetString())));
m_pClient->SendFile(f, strFileName);
}
else
{
ShowServerInfo("Please log in first.\n");
}
}
}
BOOL CClientDlg::PreTranslateMessage(MSG* pMsg)
{
// TODO: 在此添加专用代码和/或调用基类
if ((pMsg->message == WM_KEYDOWN) && (pMsg->wParam == VK_RETURN))
{
if (GetDlgItem(IDC_EDIT_SendText) == GetFocus())
{
OnClickedBtSend();
return false;
}
}
return CDialogEx::PreTranslateMessage(pMsg);
}
第三篇文章(服务端实现)
https://blog.csdn.net/qq_42662283/article/details/106493917