IOCP实现UDP Server

news2024/11/24 6:02:58

IOCP实现UDP Server

1、IOCP原理图

参考文献1:IOCP详解-阿里云开发者社区 (aliyun.com)

参考文献2:IOCP编程之基本原理 - 史D芬周 - 博客园 (cnblogs.com)

原理图

image.png

同步以及异步

image.png

image.png

2、UDP Server代码以及测试代码

// iocpudpdemo.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

// UDP Server
// RIOTest.cpp : Defines the entry point for the console application.
//
#pragma comment(lib, "ws2_32.lib")

#include <WS2tcpip.h>
#include <map>
#include <memory>
#include <cstring>
#include <thread>
#include <iostream>

using namespace std;

SOCKET g_s;
HANDLE g_hIOCP = 0;
long g_workIterations = 0;
LARGE_INTEGER g_frequency;
LARGE_INTEGER g_startCounter;
LARGE_INTEGER g_stopCounter;

volatile long g_packets = 0;

static const DWORD EXPECTED_DATA_SIZE = 8192;
static const DWORD RIO_MAX_RESULTS = 1000;
static const DWORD TIMING_THREAD_AFFINITY_MASK = 1;
static const unsigned short PORT = 8081;

struct EXTENDED_OVERLAPPED : public OVERLAPPED
{
    WSABUF buf;
};

inline void ErrorExit(
    const char* pFunction,
    const DWORD lastError)
{
    cout << "Error: " << pFunction << " failed: " << lastError << endl;
    exit(0);
}

inline void ErrorExit(
    const char* pFunction)
{
    const DWORD lastError = ::GetLastError();

    ErrorExit(pFunction, lastError);
}

inline void SetupTiming(
    const char* pProgramName,
    const bool lockToThreadForTiming = true)
{
    cout << pProgramName << endl;
    cout << "Work load: " << g_workIterations << endl;
    cout << "Max results: " << RIO_MAX_RESULTS << endl;
    if (lockToThreadForTiming)
    {
        HANDLE hThread = ::GetCurrentThread();

        if (0 == ::SetThreadAffinityMask(hThread, TIMING_THREAD_AFFINITY_MASK))
        {
            ErrorExit("SetThreadAffinityMask");
        }
    }
    if (!::QueryPerformanceFrequency(&g_frequency))
    {
        ErrorExit("QueryPerformanceFrequency");
    }
}

inline void PrintTimings(
    const char* pDirection = "Received ")
{
    LARGE_INTEGER elapsed;

    elapsed.QuadPart = (g_stopCounter.QuadPart - g_startCounter.QuadPart) / (g_frequency.QuadPart / 1000);

    cout << "Complete in " << elapsed.QuadPart << "ms" << endl;
    cout << pDirection << g_packets << " datagrams" << endl;

    if (elapsed.QuadPart != 0)
    {
        const double perSec = g_packets / elapsed.QuadPart * 1000.00;

        cout << perSec << " datagrams per second" << endl;
    }
}

inline void InitialiseWinsock()
{
    WSADATA data;
    WORD wVersionRequested = 0x202;
    if (0 != ::WSAStartup(wVersionRequested, &data))
    {
        ErrorExit("WSAStartup");
    }
}

inline SOCKET CreateSocket(
    const DWORD flags = 0)
{
    g_s = ::WSASocket(AF_INET, SOCK_DGRAM, IPPROTO_UDP, NULL, 0, flags);
    if (g_s == INVALID_SOCKET)
    {
        ErrorExit("WSASocket");
    }
    return g_s;
}

inline HANDLE CreateIOCP()
{
    g_hIOCP = ::CreateIoCompletionPort(INVALID_HANDLE_VALUE, 0, 0, 0);
    if (0 == g_hIOCP)
    {
        ErrorExit("CreateIoCompletionPort");
    }
    return g_hIOCP;
}

inline void Bind(
    SOCKET s,
    const unsigned short port)
{
    sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = INADDR_ANY;
    if (SOCKET_ERROR == ::bind(s, reinterpret_cast<struct sockaddr*>(&addr), sizeof(addr)))
    {
        ErrorExit("bind");
    }
}

template <typename TV, typename TM>
inline TV RoundDown(TV Value, TM Multiple)
{
    return((Value / Multiple) * Multiple);
}

template <typename TV, typename TM>
inline TV RoundUp(TV Value, TM Multiple)
{
    return(RoundDown(Value, Multiple) + (((Value % Multiple) > 0) ? Multiple : 0));
}

inline void StartTiming()
{
    if (!::QueryPerformanceCounter(&g_startCounter))
    {
        ErrorExit("QueryPerformanceCounter");
    }

    cout << "Timing started" << endl;
}

inline void StopTiming()
{
    if (!::QueryPerformanceCounter(&g_stopCounter))
    {
        ErrorExit("QueryPerformanceCounter");
    }

    cout << "Timing stopped" << endl;
}

inline char* AllocateBufferSpace(
    const DWORD recvBufferSize,
    const DWORD pendingRecvs,
    DWORD& bufferSize,
    DWORD& receiveBuffersAllocated)
{
    const DWORD preferredNumaNode = 0;
    const SIZE_T largePageMinimum = 0;
    SYSTEM_INFO systemInfo;
    ::GetSystemInfo(&systemInfo);
    systemInfo.dwAllocationGranularity;
    const unsigned __int64 granularity = (largePageMinimum == 0 ? systemInfo.dwAllocationGranularity : largePageMinimum);
    const unsigned __int64 desiredSize = recvBufferSize * pendingRecvs;
    unsigned __int64 actualSize = RoundUp(desiredSize, granularity);
    if (actualSize > (std::numeric_limits<DWORD>::max)())
    {
        actualSize = ((std::numeric_limits<DWORD>::max)() / granularity) * granularity;
    }
    receiveBuffersAllocated = std::min<DWORD>(pendingRecvs, static_cast<DWORD>(actualSize / recvBufferSize));
    bufferSize = static_cast<DWORD>(actualSize);
    char* pBuffer = reinterpret_cast<char*>(VirtualAllocExNuma(GetCurrentProcess(), 0, bufferSize, MEM_COMMIT | MEM_RESERVE | (largePageMinimum != 0 ? MEM_LARGE_PAGES : 0), PAGE_READWRITE, preferredNumaNode));
    if (pBuffer == 0)
    {
        ErrorExit("VirtualAlloc");
    }
    return pBuffer;
}

inline char* AllocateBufferSpace(
    const DWORD recvBufferSize,
    const DWORD pendingRecvs,
    DWORD& receiveBuffersAllocated)
{
    DWORD notUsed;
    return AllocateBufferSpace(recvBufferSize, pendingRecvs, notUsed, receiveBuffersAllocated);
}

inline void PostIOCPRecvs(
    const DWORD recvBufferSize,
    const DWORD pendingRecvs)
{
    DWORD totalBuffersAllocated = 0;

    while (totalBuffersAllocated < pendingRecvs)
    {
        DWORD receiveBuffersAllocated = 0;
        char* pBuffer = AllocateBufferSpace(recvBufferSize, pendingRecvs, receiveBuffersAllocated);
        totalBuffersAllocated += receiveBuffersAllocated;
        DWORD offset = 0;
        const DWORD recvFlags = 0;
        EXTENDED_OVERLAPPED* pBufs = new EXTENDED_OVERLAPPED[receiveBuffersAllocated];
        DWORD bytesRecvd = 0;
        DWORD flags = 0;
        for (DWORD i = 0; i < receiveBuffersAllocated; ++i)
        {
            EXTENDED_OVERLAPPED* pOverlapped = pBufs + i;
            ZeroMemory(pOverlapped, sizeof(EXTENDED_OVERLAPPED));
            pOverlapped->buf.buf = pBuffer + offset;
            pOverlapped->buf.len = recvBufferSize;
            offset += recvBufferSize;
            if (SOCKET_ERROR == ::WSARecvFrom(g_s, &(pOverlapped->buf), 1, &bytesRecvd, &flags, NULL, NULL, pOverlapped, 0))
            {
                const DWORD lastError = ::GetLastError();

                if (lastError != ERROR_IO_PENDING)
                {
                    ErrorExit("WSARecv", lastError);
                }
            }
        }

        if (totalBuffersAllocated != pendingRecvs)
        {
            cout << pendingRecvs << " receives pending" << endl;
        }
    }

    cout << totalBuffersAllocated << " total receives pending" << endl;
}


int main(int argc, char* argv[])
{
    std::map<std::size_t, std::pair<std::size_t, std::shared_ptr<char>>> packets;
    SetupTiming("IOCP UDP");
    InitialiseWinsock();
    SOCKET s = CreateSocket(WSA_FLAG_OVERLAPPED);
    HANDLE hIOCP = CreateIOCP();
    Bind(s, PORT);
    if (0 == ::CreateIoCompletionPort(reinterpret_cast<HANDLE>(s), hIOCP, 0, 0))
    {
        ErrorExit("CreateIoCompletionPort");
    }
    struct sockaddr_in sname;
    int snamesize = sizeof(struct sockaddr_in);
    ::getsockname(s, (struct sockaddr*)&sname, &snamesize);
    std::cout << sname.sin_port << std::endl;
    std::cout << ntohs(sname.sin_port) << std::endl;
    PostIOCPRecvs(8192, 2000);
    bool done = false;
    DWORD numberOfBytes = 0;
    ULONG_PTR completionKey = 0;
    OVERLAPPED* pOverlapped = 0;
    if (!::GetQueuedCompletionStatus(hIOCP, &numberOfBytes, &completionKey, &pOverlapped, INFINITE))
    {
        ErrorExit("GetQueuedCompletionStatus");
    }
    StartTiming();

    //std::thread killIOCP([&]() {
    //    std::cout << "iocp kill start" << std::endl;
    //    std::this_thread::sleep_for(std::chrono::seconds(5));
    //    std::cout << "kill iocp" << std::endl;
    //    CloseHandle(hIOCP);
    //    });
    //killIOCP.detach();

    DWORD bytesRecvd = 0;
    DWORD flags = 0;
    std::size_t times = 0;
    do
    {
        if (numberOfBytes == EXPECTED_DATA_SIZE || numberOfBytes == 100)
        {
            g_packets++;
            EXTENDED_OVERLAPPED* pExtOverlapped = static_cast<EXTENDED_OVERLAPPED*>(pOverlapped);
            if (SOCKET_ERROR == ::WSARecvFrom(g_s, &(pExtOverlapped->buf), 1, &bytesRecvd, &flags, NULL, NULL, pExtOverlapped, 0))
            {
                const DWORD lastError = ::GetLastError();
                std::shared_ptr<char> packet(new char[numberOfBytes]);
                memmove(packet.get(), pExtOverlapped->buf.buf, numberOfBytes);
                if (numberOfBytes == 100) {
                    std::cout << pExtOverlapped->buf.buf[2] << std::endl;
                }
                auto ppp = std::make_pair<std::size_t, std::shared_ptr<char>&>(numberOfBytes, packet);
                packets.insert({ g_packets,ppp });
                if (lastError != ERROR_IO_PENDING)
                {
                    ErrorExit("WSARecv", lastError);
                }
            }
        }
        else
        {
            g_packets++;
            EXTENDED_OVERLAPPED* pExtOverlapped = static_cast<EXTENDED_OVERLAPPED*>(pOverlapped);
            if (SOCKET_ERROR == ::WSARecvFrom(g_s, &(pExtOverlapped->buf), 1, &bytesRecvd, &flags, NULL, NULL, pExtOverlapped, 0))
            {
                const DWORD lastError = ::GetLastError();
                std::shared_ptr<char> packet(new char[numberOfBytes]);
                memmove(packet.get(), pExtOverlapped->buf.buf, numberOfBytes);
                auto ppp = std::make_pair<std::size_t, std::shared_ptr<char>&>(numberOfBytes, packet);
                packets.insert({ g_packets,ppp });
                std::cout << "use count:" << packet.use_count() << std::endl;
                if (lastError != ERROR_IO_PENDING)
                {
                    ErrorExit("WSARecv", lastError);
                }
            }
            std::cout << "packets size: " << packets.size() << std::endl;
            StopTiming();
            done = true;
        }
        if (!done)
        {
            if (!::GetQueuedCompletionStatus(hIOCP, &numberOfBytes, &completionKey, &pOverlapped, INFINITE))
            {
                DWORD error = GetLastError();
                if (ERROR_ABANDONED_WAIT_0 == error || ERROR_INVALID_HANDLE == error) {
                    StopTiming();
                    std::cout << error << std::endl;
                    break;
                }
                ErrorExit("GetQueuedCompletionStatus");
            }
        }
    } while (!done);
    PrintTimings();
    packets.clear();
    return 0;
}

测试代码

#include <boost/asio.hpp>
#include <cstring>
#include <iostream>

char* makeMem(size_t size){
    char* mem = (char*)malloc(size);
    memset(mem,'1',size);
    memset(mem+(size-8296),'2',8296);
    return mem;
}

int main(){
    boost::asio::io_context context;
    boost::asio::ip::udp::endpoint destEndpoint = boost::asio::ip::udp::endpoint(boost::asio::ip::make_address("10.10.1.40"),8081);

    boost::asio::ip::udp::socket transmitter = boost::asio::ip::udp::socket(context,boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), 10120));
    size_t size = 20*1024*1024 + 100;// 20MB
    char* mem = makeMem(size);
    char* sendData = mem;

    std::size_t payload = 8192;
    std::size_t leftLastSize = size %payload;
    std::size_t sendTimes = size/payload;
    char headerData[100] = {3};
    memset(headerData,3,sizeof(headerData));
    transmitter.send_to(boost::asio::buffer(headerData, sizeof(headerData)), destEndpoint);
    for(size_t idx =0;idx<sendTimes;++idx,sendData+=payload){
        transmitter.send_to(boost::asio::buffer(sendData, payload), destEndpoint);
        std::cout << idx<<std::endl;
        //std::this_thread::sleep_for(std::chrono::milliseconds(1));
    }
    transmitter.send_to(boost::asio::buffer(sendData, leftLastSize), destEndpoint);
    std::cout << "------------"<<std::endl;
    std::this_thread::sleep_for(std::chrono::seconds(10));

    sendData = mem;
    transmitter.send_to(boost::asio::buffer(headerData, sizeof(headerData)), destEndpoint);
    for(size_t idx =0;idx<sendTimes;++idx,sendData+=payload){
        transmitter.send_to(boost::asio::buffer(sendData, payload), destEndpoint);
        std::cout << idx<<std::endl;
        //std::this_thread::sleep_for(std::chrono::milliseconds(1));
    }
    transmitter.send_to(boost::asio::buffer(sendData, leftLastSize), destEndpoint);


    char tailerData[10] = {9};
    transmitter.send_to(boost::asio::buffer(tailerData, sizeof(tailerData)), destEndpoint);

    delete mem;
    return 0;
}

最后,推荐一个项目,上述代码基本来自于该项目

LenHolgate/RIO: Code that explores the Windows Registered I/O Networking Extensions (github.com)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1633014.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

再谈钓鱼邮件

再谈钓鱼邮件 概述 最近对邮件的防御策略进行了更新&#xff0c;结合威胁情报和安全沙箱对收到的钓鱼邮件进行了分析&#xff0c;期望这些案例能对大家有所帮助。 网关上拦截的钓鱼邮件基本可以分三个类别&#xff1a;链接钓鱼邮件、附件钓鱼邮件以及邮件头伪造钓鱼邮件&…

在谷歌浏览器访问特定的网站 提示此网站无法提供安全连接

1、问题描述&#xff1a; 最近通过谷歌浏览器访问某些网址提示此网站无法提供安全连接&#xff0c;换一个浏览器就能正确打开&#xff01; 例子如下&#xff1a; 访问 https://baijiahao.baidu.com/s?id1788533041823242656 2、查找原因 通过控制台发现请求未有响应码&#xf…

【数据分析面试】34.填充NaN值 (Python:groupby/sort_value/ffill)

题目&#xff1a;填充NaN值 &#xff08;Python) 给定一个包含三列的DataFrame&#xff1a;client_id、ranking、value 编写一个函数&#xff0c;将value列中的NaN值用相同client_id的前一个非NaN值填充&#xff0c;按升序排列。 如果不存在前一个client_id&#xff0c;则返…

小红书从记忆机制解读信息检索,提出新范式获得 EACL Oral

近日&#xff0c;来自小红书搜索算法团队的论文《Generative Dense Retrieval: Memory Can Be a Burden》被自然语言处理领域国际会议 EACL 2024 接收为 Oral&#xff0c;接受率为 11.32%&#xff08;144/1271&#xff09;。 他们在论文中提出了一种新颖的信息检索范式——生成…

python环境安装jupyter

安装完毕之后下一步可以参考&#xff1a;配置jupyter的启动路径-CSDN博客 1 前提条件&#xff1a;python环境 系统&#xff1a;win10 python&#xff1a;本地已经有python&#xff0c;可以查看本地的python版本&#xff1a; C:\Users\PC>python --version Python 3.8.10 …

为什么本国货币的贬值会导致本国物价的上涨

本国货币贬值意味着其对外国货币的汇率下降&#xff0c;也就是说&#xff0c;同样数量的本国货币现在能兑换的外国货币减少了。这种情况下&#xff0c;本国货币的购买力相对于外国货币减弱了。本国货币贬值可能导致本国物价上涨的几个原因&#xff1a; 进口成本上升&#xff1a…

38.WEB渗透测试-信息收集-信息收集-企业信息收集(5)

免责声明&#xff1a;内容仅供学习参考&#xff0c;请合法利用知识&#xff0c;禁止进行违法犯罪活动&#xff01; 内容参考于&#xff1a; 易锦网校会员专享课 上一个内容&#xff1a;37.WEB渗透测试-信息收集-企业信息收集&#xff08;4&#xff09; 上个内容用到了cdn&am…

Windows Server 评估版转换(升级)为完整版

临时方法 获取 Windows Server 的剩余宽限期 Slmgr /dliWindows Server免费试用期可以使用以下命令合法延长5次&#xff0c;共180天&#xff1a; slmgr /rearm这意味着所评估的 Windows Server 的最长可用时间为 3 年 ( 180 days * 6)。 试用期到期后&#xff0c;Windows S…

Python对Excel两列数据进行运算

&#x1f47d;发现宝藏 前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c;忍不住分享一下给大家。【点击进入巨牛的人工智能学习网站】。 Python对Excel两列数据进行运算 在日常工作中&#xff0c;经常会遇到需要对Excel表格中的数…

win中python中OpenCV使用cv2.imshow()报错的解决办法

1. 问题 cv2.error: OpenCV(4.9.0) D:\a\opencv-python\opencv-python\opencv\modules\highgui\src\window.cpp:1272: error: (-2:Unspecified error) The function is not implemented. Rebuild the library with Windows, GTK 2.x or Cocoa support. If you are on Ubuntu o…

STM32读写备份寄存器BKP

今天学习的读写STM32的备份寄存器BKP的步骤&#xff0c;这节知识是比较简单的&#xff0c;一共也就两大部&#xff1a; 这个BKP寄存器的意思就是在芯片的VB引脚上接个电池&#xff0c;就能保存其寄存器中的数据掉电不丢失。先来看看电池的接法&#xff1a; 好&#xff0c;下面…

3分钟了解拍摄VR全景需要哪些硬件

VR全景图片是一张水平方向360度&#xff0c;垂直方向180度&#xff0c; 图片尺寸宽高比为2:1的图片。 通过720yun APP或720yun官网上传生成全景H5页面&#xff0c;即可360度全方位观看画面中的景象。 拍摄VR全景有很多方法&#xff0c;下面介绍用单反相机、全景相机、智能手机…

【Paddle】PCA线性代数基础 + 领域应用:人脸识别算法(1.1w字超详细:附公式、代码)

【Paddle】PCA线性代数基础及领域应用 写在最前面一、PCA线性代数基础1. PCA的算法原理2. PCA的线性代数基础2.1 标准差 Standard Deviation2.2 方差 Variance2.3 协方差 Covariance2.4 协方差矩阵 The Covariance Matrix2.5 paddle代码demo①&#xff1a;计算协方差矩阵2.6 特…

华院计算登榜『2024福布斯中国人工智能科技企业TOP 50』

4月28日&#xff0c;福布斯中国正式发布“2024福布斯中国人工智能科技企业TOP 50”榜单。华院计算凭借其在人工智能领域的卓越成就与深远影响力&#xff0c;荣膺殊荣&#xff0c;成功跻身榜单。 工业和信息化部2024年4月表示&#xff0c;中国人工智能企业数量已超过4,500家。AI…

你的3D模型不是数字孪生!

大型资产的新技术往往是根据其带来运营效率提升的能力来判断的。 但是&#xff0c;当一项令人兴奋的创新出现时&#xff0c;运营商通常会承担经过计算的风险并对其潜力进行投资&#xff0c;即使该技术缺乏保证在规定时间范围内带来收益的验证。 数字孪生&#xff08;digital …

学习笔记:能量信号与功率信号(一)

目录 一、能量信号&#xff08;Energy Signal&#xff09; 二、功率信号&#xff08;Power Signal&#xff09; 三、信号关系图 四、总结 能量信号和功率信号是信号分析中两个基本的概念&#xff0c;它们主要用来描述信号在时间域中能量分布的特性&#xff0c;对于理解信号…

LLM - 大语言模型(LLM) 的 评估体系

欢迎关注我的CSDN:https://spike.blog.csdn.net/ 本文地址:https://blog.csdn.net/caroline_wendy/article/details/138160155 大语言模型(LLM)的评估是复杂且多维的过程,涉及多个方面,包括评估体系、评估方法、评估实践。评估体系包括评估数据集、模型输出、样本/输出变换…

idm下载速度慢解决办法 idm批量下载怎么用 idm优化下载速度 Internet Download Manager解决下载速度慢的方法教程

IDM (Internet Download Manager)是一款兼容性大&#xff0c;支持多种语言的下载管理软件&#xff0c;它可以自动检测并下载网页上的内容&#xff0c;这正是这一优点&#xff0c;使得它受到了广大用户的喜爱。但是在下载的过程中&#xff0c;我们会遇到idm下载速度慢怎么回事&a…

酷克数据启动鲲鹏原生应用开发合作

4月28日&#xff0c;北京酷克数据科技有限公司&#xff08;以下简称“酷克数据”&#xff09;与华为举办鲲鹏原生应用开发启动仪式。酷克数据将基于鲲鹏硬件底座、OpenEuler、开发套件Kunpeng DevKit、应用使能套件Kunpeng BoostKit开展面向金融、政务、电信、能源、交通等重点…

推荐七款公司防泄密软件|数据防泄漏软件排行榜

最近常常有客户反馈&#xff1a;公司日夜辛苦做的设计图纸出现在竞品公司手中&#xff1b;客户名单泄露&#xff0c;客户被离职员工撬走&#xff1b;带有商业机密的U盘丢失……一些列问题困扰着大多数企业&#xff0c;每一次泄密事件的发生都会给企业带来高额的财产经济损失。 …