1. 최초 커밋

This commit is contained in:
이형구 2021-05-02 03:45:58 +09:00
commit bab31d6d58
5 changed files with 923 additions and 0 deletions

371
.gitignore vendored Normal file
View File

@ -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

31
IOCP_ECHO.sln Normal file
View File

@ -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

View File

@ -0,0 +1,154 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{A14B4D24-D425-4762-A44A-8BD8DEF52AAC}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>IOCP_ECHO_SERVER</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="main.cpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="소스 파일">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="헤더 파일">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;hm;inl;inc;xsd</Extensions>
</Filter>
<Filter Include="리소스 파일">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="main.cpp">
<Filter>소스 파일</Filter>
</ClCompile>
</ItemGroup>
</Project>

345
IOCP_ECHO_SERVER/main.cpp Normal file
View File

@ -0,0 +1,345 @@
#include <iostream>
#include <process.h>
#include <list>
#include <algorithm>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
#define IP_ADDRESS 127.0.0.1
#define PORT_ADDRESS 5000
//template <typename _Type>
//class COverLapped : public OVERLAPPED
//{
//public:
// COverLapped(void)
// {
// m_WsaBuf.len = BUFSIZE;
// m_WsaBuf.buf = reinterpret_cast<char*>(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<HANDLE>(_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<CIocpSocket*>(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 = dDataLength<BUFSIZE?dDataLength:BUFSIZE;
m_SendBuf.m_WsaBuf.buf = (CHAR*)&pData[dLessSendCount-dDataLength];
dDataLength -= m_SendBuf.m_WsaBuf.len;
DWORD dwFlags = 0;
WSASend(m_Socket, &m_SendBuf.m_WsaBuf, 1, NULL, 0, (OVERLAPPED*)&m_SendBuf, NULL);
}
}
void recv(void)
{
COverLapped *pOverlapped = new COverLapped();
memset((OVERLAPPED*)pOverlapped, 0, sizeof(OVERLAPPED));
pOverlapped->m_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;
}