IOCP套接字,不知道下一步该做什么

时间:2013-11-09 22:41:46

标签: c++ sockets iocp

我学会了如何使用Windows Message Proc创建套接字并打开FD_CONNECT,FD_ACCEPT,FD_CLOSE等。我使用了:WSAAsyncSelect(socket, WindowHandle, WM_SOCKET, FD_READ | FD_WRITE | FD_CONNECT | FD_CLOSE | FD_ACCEPT)

这让我知道套接字:接受,关闭,接收数据,而无需轮询。

现在我正在尝试学习为控制台应用程序做同样的操作,但使用IOCP。

我写了以下内容:

#include <Winsock2.h>
#include <Ws2tcpip.h>
#include <Windows.h>
#include <iostream>
#include <thread>
#include <stdexcept>
#include <cstring>

class Socket
{
    private:
        typedef struct
        {
            OVERLAPPED Overlapped;
            WSABUF DataBuf;
            char Buffer[1024];
            unsigned int BytesSent;
            unsigned int BytesReceived;
        } PER_IO_OPERATION_DATA;

        typedef struct
        {
            SOCKET Sock;
        } PER_HANDLE_DATA;


    protected:
        void Close();
        std::function<void(HANDLE)> Worker;

    public:
        Socket();
        bool Start(std::string Address, unsigned int Port, bool Listen);

        void Read(char* Buffer, int bufflen); //reads from a socket.
        void Write(char* Buffer, int bufflen); //writes to a socket.
        bool Accept();  //accepts a socket.

        virtual void OnRead();   //Called when Reading.
        virtual void OnWrite();  //Called when Writing.
        virtual void OnAccept(); //Called when a socket has been accepted.
        virtual void OnConnect();  //Called when connected.
        virtual void OnDisconnect(); //Called when disconnected.
};

bool Socket::Start(std::string Address, unsigned int Port, bool Listen)
{
    WSADATA wsaData;
    SOCKET sock = 0;
    struct sockaddr_in* sockaddr_ipv4;

    //WSA Startup and getaddrinfo, etc.. here..

    //Create IOCP Handle and worker threads.
    HANDLE IOCPPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE, nullptr, 0, 0);
    if (!IOCPPort)
    {
        this->Close();
        throw std::runtime_error("Error: Creating IOCP Failed With Error: " + std::to_string(GetLastError()));
    }

    SYSTEM_INFO SystemInfo = {0};
    GetSystemInfo(&SystemInfo);
    for (std::size_t I = 0; I < SystemInfo.dwNumberOfProcessors * 2; ++I)
    {
        std::thread(this->Worker, IOCPPort).detach();
    }

    //Set the socket to overlapped.
    if ((sock = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, nullptr, 0, WSA_FLAG_OVERLAPPED)) == INVALID_SOCKET)
    {
        this->Close();
        throw std::runtime_error("Error: ");
    }

    struct sockaddr_in SockAddr;
    std::memset(&SockAddr, 0, sizeof(SockAddr));
    SockAddr.sin_port = htons(Port);
    SockAddr.sin_family = AF_INET;
    SockAddr.sin_addr.s_addr = (Address == "INADDR_ANY" ? htonl(INADDR_ANY) : inet_addr(Address.c_str()));

    //If it is a server socket being created, bind it.
    if (Listen && (bind(sock, reinterpret_cast<SOCKADDR*>(&SockAddr), sizeof(SockAddr)) == SOCKET_ERROR))
    {
        this->Close();
        throw std::runtime_error("Error: ");
    }

    //If it is a server socket, start listenening.
    if (Listen && (listen(sock, SOMAXCONN) == SOCKET_ERROR))
    {
        this->Close();
        throw std::runtime_error("Error: ");
    }

    //Otherwise it is a client socket so just connected..
    //if(!Listen && (connect(this->socket, reinterpret_cast<SOCKADDR*>(&SockAddr), sizeof(SockAddr)) == SOCKET_ERROR))


    //Associate this socket with a completion port.
    if (CreateIoCompletionPort(reinterpret_cast<HANDLE>(sock), IOCPPort, 0, 0) != IOCPPort)
    {
        this->Close();
        throw std::runtime_error("Error: ");
    }

    //setsockopt(sock, SOL_SOCKET, SO_UPDATE_ACCEPT_CONTEXT, (char *)sdListen, sizeof(sdListen));
}

然而,现在我被卡住了。我不确定在创建IoCompletionPort后我需要做什么。我如何知道套接字何时被接受,以便我可以调用OnAccept,或者如何判断何时有数据需要读取,以便我可以调用OnRead?我浏览了谷歌上的所有页面,但找不到与OnRead,OnAccept或OnWrite类似的任何内容。

我只是想让它可扩展,并且在没有使用事件或消息循环的情况下进行回调。我在google上看到的唯一让我感兴趣的是IOCP,但我完全迷失了。我还需要做什么?

1 个答案:

答案 0 :(得分:0)

很久以前我写了一些关于IOCP服务器设计的文章,我也有一些你可以下载的代码,为你做基础知识。

您可以获取代码并找到here中文章的链接。它们可以帮助您了解接下来会发生什么以及如何构建IOCP客户端或服务器。