From bab31d6d58f44634e2079df788b725c96f5085ce Mon Sep 17 00:00:00 2001 From: chodadoo Date: Sun, 2 May 2021 03:45:58 +0900 Subject: [PATCH] =?UTF-8?q?1.=20=EC=B5=9C=EC=B4=88=20=EC=BB=A4=EB=B0=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 371 ++++++++++++++++++ IOCP_ECHO.sln | 31 ++ IOCP_ECHO_SERVER/IOCP_ECHO_SERVER.vcxproj | 154 ++++++++ .../IOCP_ECHO_SERVER.vcxproj.filters | 22 ++ IOCP_ECHO_SERVER/main.cpp | 345 ++++++++++++++++ 5 files changed, 923 insertions(+) create mode 100644 .gitignore create mode 100644 IOCP_ECHO.sln create mode 100644 IOCP_ECHO_SERVER/IOCP_ECHO_SERVER.vcxproj create mode 100644 IOCP_ECHO_SERVER/IOCP_ECHO_SERVER.vcxproj.filters create mode 100644 IOCP_ECHO_SERVER/main.cpp diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5f95e29 --- /dev/null +++ b/.gitignore @@ -0,0 +1,371 @@ + +# Created by https://www.toptal.com/developers/gitignore/api/visualstudio +# Edit at https://www.toptal.com/developers/gitignore?templates=visualstudio + +### VisualStudio ### +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*[.json, .xml, .info] + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +### VisualStudio Patch ### +# Additional files built by Visual Studio +*.tlog + +# End of https://www.toptal.com/developers/gitignore/api/visualstudio \ No newline at end of file diff --git a/IOCP_ECHO.sln b/IOCP_ECHO.sln new file mode 100644 index 0000000..39408eb --- /dev/null +++ b/IOCP_ECHO.sln @@ -0,0 +1,31 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.30804.86 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "IOCP_ECHO_SERVER", "IOCP_ECHO_SERVER\IOCP_ECHO_SERVER.vcxproj", "{A14B4D24-D425-4762-A44A-8BD8DEF52AAC}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {A14B4D24-D425-4762-A44A-8BD8DEF52AAC}.Debug|x64.ActiveCfg = Debug|x64 + {A14B4D24-D425-4762-A44A-8BD8DEF52AAC}.Debug|x64.Build.0 = Debug|x64 + {A14B4D24-D425-4762-A44A-8BD8DEF52AAC}.Debug|x86.ActiveCfg = Debug|Win32 + {A14B4D24-D425-4762-A44A-8BD8DEF52AAC}.Debug|x86.Build.0 = Debug|Win32 + {A14B4D24-D425-4762-A44A-8BD8DEF52AAC}.Release|x64.ActiveCfg = Release|x64 + {A14B4D24-D425-4762-A44A-8BD8DEF52AAC}.Release|x64.Build.0 = Release|x64 + {A14B4D24-D425-4762-A44A-8BD8DEF52AAC}.Release|x86.ActiveCfg = Release|Win32 + {A14B4D24-D425-4762-A44A-8BD8DEF52AAC}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {A7B0780A-EFFB-4270-B361-E138CFDE6D46} + EndGlobalSection +EndGlobal diff --git a/IOCP_ECHO_SERVER/IOCP_ECHO_SERVER.vcxproj b/IOCP_ECHO_SERVER/IOCP_ECHO_SERVER.vcxproj new file mode 100644 index 0000000..ab5cd38 --- /dev/null +++ b/IOCP_ECHO_SERVER/IOCP_ECHO_SERVER.vcxproj @@ -0,0 +1,154 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + {A14B4D24-D425-4762-A44A-8BD8DEF52AAC} + Win32Proj + IOCP_ECHO_SERVER + 10.0 + + + + Application + true + v142 + Unicode + + + Application + false + v142 + true + Unicode + + + Application + true + v142 + Unicode + + + Application + false + v142 + true + Unicode + + + + + + + + + + + + + + + + + + + + + true + + + true + + + false + + + false + + + + + + Level3 + Disabled + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + + + + + + + Level3 + Disabled + _DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + + + + + Level3 + + + MaxSpeed + true + true + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + Level3 + + + MaxSpeed + true + true + NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + + + + + \ No newline at end of file diff --git a/IOCP_ECHO_SERVER/IOCP_ECHO_SERVER.vcxproj.filters b/IOCP_ECHO_SERVER/IOCP_ECHO_SERVER.vcxproj.filters new file mode 100644 index 0000000..fd7ef2b --- /dev/null +++ b/IOCP_ECHO_SERVER/IOCP_ECHO_SERVER.vcxproj.filters @@ -0,0 +1,22 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + 소스 파일 + + + \ No newline at end of file diff --git a/IOCP_ECHO_SERVER/main.cpp b/IOCP_ECHO_SERVER/main.cpp new file mode 100644 index 0000000..f1bb046 --- /dev/null +++ b/IOCP_ECHO_SERVER/main.cpp @@ -0,0 +1,345 @@ +#include + +#include +#include +#include + +#include + +#pragma comment(lib, "ws2_32.lib") + +#define IP_ADDRESS 127.0.0.1 +#define PORT_ADDRESS 5000 + +//template +//class COverLapped : public OVERLAPPED +//{ +//public: +// COverLapped(void) +// { +// m_WsaBuf.len = BUFSIZE; +// m_WsaBuf.buf = reinterpret_cast(buffer); +// } +// virtual ~COverLapped(void) {} +// +//private: +//protected: +//public: +// static const UINT BUFSIZE = 4096; +// +// typedef enum _E_OP +// { +// READY = 0x00, +// CREATE, +// BIND, +// LISTEN, +// CONNECT, +// ACCEPT, +// SEND, +// RECV, +// }E_OP; +// +// E_OP m_eOperator; +// +// WSABUF m_WsaBuf; +// _Type buffer[BUFSIZE]; +//}; + +static const UINT BUFSIZE = 4096; + +class COverLapped : public OVERLAPPED +{ +public: + COverLapped(void) : m_eOperator(E_OP::READY) + { + } + ~COverLapped(void) {} + +private: +protected: +public: + typedef enum _E_OP + { + READY = 0x00, + CREATE, + BIND, + LISTEN, + CONNECT, + ACCEPT, + SEND, + RECV, + }E_OP; + + E_OP m_eOperator; + + WSABUF m_WsaBuf; + CHAR m_buffer[BUFSIZE]; +}; + +class CIocpSocket +{ +public: + CIocpSocket(void) {} + ~CIocpSocket(void) + { + closesocket(m_Socket); + WSACleanup(); + } + +private: + CIocpSocket& operator=(const CIocpSocket&) {} + + SOCKET m_Socket; + SOCKADDR_IN m_SocketAddr_in; + + HANDLE m_IocpHandle; + + HANDLE *m_ThreadHandle; + + COverLapped m_SendBuf; + COverLapped m_RecvBuf; + +protected: +public: + bool CreateIocp(void) + { + WSADATA wsaData; + if (WSAStartup(MAKEWORD(2, 2), &wsaData)) + { + int nErrorCode = WSAGetLastError(); + return false; + } + + m_IocpHandle = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0); + + if (!m_IocpHandle) + { + int nErrorCode = WSAGetLastError(); + return false; + } + + m_Socket = WSASocket(PF_INET, SOCK_STREAM, 0, NULL, 0, WSA_FLAG_OVERLAPPED); + + if (m_Socket == INVALID_SOCKET) + { + int nErrorCode = WSAGetLastError(); + return false; + } + + // PC ҽ + SYSTEM_INFO systemInfo; + GetSystemInfo(&systemInfo); + + // CPU + UINT dThreadCount = systemInfo.dwNumberOfProcessors * 2; + m_ThreadHandle = new HANDLE[dThreadCount]; + for (int i = 0; i < 1; ++i) + { + m_ThreadHandle[i] = reinterpret_cast(_beginthreadex(NULL, NULL, IOCP_QUEUE_THREAD_PROC, (LPVOID)this, 0, NULL)); + } + + return true; + } + + bool Bind(UINT dPort) + { + memset(&m_SocketAddr_in, 0, sizeof(SOCKADDR_IN)); + m_SocketAddr_in.sin_family = AF_INET; + m_SocketAddr_in.sin_addr.s_addr = htonl(INADDR_ANY); + m_SocketAddr_in.sin_port = htons(dPort); + + if (bind(m_Socket, (SOCKADDR *)&m_SocketAddr_in, sizeof(SOCKADDR_IN)) == SOCKET_ERROR) + { + int nErrorCode = WSAGetLastError(); + return false; + } + + return true; + } + + bool Listen(UINT dBacklog = SOMAXCONN) + { + if (listen(m_Socket, dBacklog) == SOCKET_ERROR) + { + int nErrorCode = WSAGetLastError(); + return false; + } + + return true; + } + + bool Connect(LPTSTR pszIpAddress, WORD wPort) + { + m_SocketAddr_in.sin_family = AF_INET; + int nAddrLen = sizeof(SOCKADDR_IN); + WSAStringToAddress(pszIpAddress, AF_INET, NULL, (SOCKADDR*)&m_SocketAddr_in, &nAddrLen); + m_SocketAddr_in.sin_port = htons(wPort); + + //if (WSAConnect(m_Socket, (struct sockaddr*)&m_SocketAddr_in, sizeof(SOCKADDR_IN), NULL, NULL, NULL, NULL) < 0) + if (connect(m_Socket, (struct sockaddr*)&m_SocketAddr_in, sizeof(SOCKADDR_IN)) < 0) + { + int err = WSAGetLastError(); + return false; + } + + return true; + } + + CIocpSocket* Accept(void) + { + int nAddrLen = sizeof(SOCKADDR_IN); + + CIocpSocket *pIocpClient = new CIocpSocket(); + pIocpClient->m_Socket = accept(m_Socket, (SOCKADDR*)&pIocpClient->m_SocketAddr_in, &nAddrLen); + + if (pIocpClient->m_Socket == INVALID_SOCKET) + { + delete pIocpClient; + + int err = WSAGetLastError(); + return NULL; + } + + memcpy(&(pIocpClient->m_SocketAddr_in), &pIocpClient->m_SocketAddr_in, nAddrLen); + + if (!CreateIoCompletionPort((HANDLE)pIocpClient->m_Socket, m_IocpHandle, (DWORD)pIocpClient, 0)) + { + delete pIocpClient; + + int nErrorCode = WSAGetLastError(); + return false; + } + + return pIocpClient; + } + + static UINT __stdcall IOCP_QUEUE_THREAD_PROC(LPVOID lpvoid) + { + CIocpSocket* pCIocpSocket = static_cast(lpvoid); + + while (TRUE) + { + DWORD dwNumberOfBytesTransferred = 0; + CIocpSocket *pCIocpSocket_Target = NULL; + COverLapped *pOverlapped = NULL; + //PER_IO_DATA *pPER_IO_DATA = NULL; + + BOOL bResult = GetQueuedCompletionStatus(pCIocpSocket->m_IocpHandle, + &dwNumberOfBytesTransferred, + (LPDWORD)&pCIocpSocket_Target, + //(LPOVERLAPPED*)&pPER_IO_DATA, + (LPOVERLAPPED*)&pOverlapped, + INFINITE); + + if (bResult == FALSE || dwNumberOfBytesTransferred == 0) + { + closesocket(pCIocpSocket_Target->m_Socket); + pCIocpSocket_Target->OnDisconnect(); + continue; + } + + //switch (pPER_IO_DATA->rwMode) + switch (pOverlapped->m_eOperator) + { + case COverLapped::E_OP::SEND: + pCIocpSocket_Target->OnSend(pOverlapped->m_WsaBuf.buf, dwNumberOfBytesTransferred); + break; + case COverLapped::E_OP::RECV: + pCIocpSocket_Target->OnRecv(pOverlapped->m_WsaBuf.buf, dwNumberOfBytesTransferred); + pCIocpSocket_Target->send((BYTE*)pOverlapped->m_WsaBuf.buf, dwNumberOfBytesTransferred); + break; + } + } + + return 0; + } + + void send(BYTE *pData, UINT dDataLength) + { + UINT dLessSendCount = dDataLength; + while ((int)dDataLength >= 1) + { + memset((OVERLAPPED*)&m_SendBuf, 0, sizeof(OVERLAPPED)); + m_SendBuf.m_eOperator = COverLapped::E_OP::SEND; + m_SendBuf.m_WsaBuf.len = dDataLengthm_eOperator = COverLapped::E_OP::RECV; + pOverlapped->m_WsaBuf.len = BUFSIZE; + pOverlapped->m_WsaBuf.buf = pOverlapped->m_buffer; + + //PER_IO_DATA *pPER_IO_DATA = new PER_IO_DATA(); + //memset(&(pPER_IO_DATA->overlapped), 0, sizeof(OVERLAPPED)); + //pPER_IO_DATA->rwMode = 2; + //pPER_IO_DATA->wsaBuf.len = BUFSIZE; + //pPER_IO_DATA->wsaBuf.buf = pPER_IO_DATA->buffer; + + DWORD dwFlags = 0; + + WSARecv(m_Socket, &(pOverlapped->m_WsaBuf), 1/*pOverlapped->BUFSIZE*/, NULL, &dwFlags, (OVERLAPPED*)pOverlapped, NULL); + //WSARecv(m_Socket, &(pPER_IO_DATA->wsaBuf), 1/*pOverlapped->BUFSIZE*/, NULL, &dwFlags, &(pPER_IO_DATA->overlapped), NULL); + } + + //virtual void OnAccept(void); + //virtual void OnConnect(void); + virtual void OnRecv(CHAR *pData, UINT dDataLength) + { + printf("CIocpSocket OnRecv(Port : %d) : %s\r\n", m_SocketAddr_in.sin_port, pData); + } + + virtual void OnSend(CHAR *pData, UINT dDataLength) + { + printf("CIocpSocket OnSend(Port : %d) : %s\r\n", m_SocketAddr_in.sin_port, pData); + } + + virtual void OnDisconnect(void) + { + printf("CIocpSocket OnDisconnect\r\n"); + } +}; + +class CIocpServer : public CIocpSocket +{ +public: + +private: +protected: +public: + void run(void) + { + CreateIocp(); + Bind(5000); + Listen(); + + while (TRUE) + { + CIocpSocket *pClientSocket = Accept(); + pClientSocket->recv(); + } + } + + virtual void OnRecv(BYTE *pData, UINT dDataLength) + { + printf("CIocpServer OnRecv : %s\r\n", pData); + } +}; + +int main(int argc, char *argv[]) +{ + CIocpServer is; + + is.run(); + + return 0; +} \ No newline at end of file