• 服务器IO复用reactor模式


    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    const int MAX_CLIENTS = 10;
    const int BUFFER_SIZE = 1024;
    const int MAX_THREADS = 4;
    
    struct EventData
    {
        int clientSocket;
    };
    
    class ThreadPool
    {
    public:
        ThreadPool(size_t numThreads)
        {
            for (size_t i = 0; i < numThreads; ++i)
            {
                threads_.emplace_back([this]
                                      {
                    while (true) {
                        std::function<void()> task;
                        {
                            std::unique_lock<std::mutex> lock(mutex_);
                            condition_.wait(lock, [this] { return stop_ || !tasks_.empty(); });
    
                            if (stop_ && tasks_.empty()) {
                                return;
                            }
    
                            task = std::move(tasks_.front());
                            tasks_.pop();
                        }
                        //std::cout << "task(); " << std::endl;
                        task();
                    } });
            }
        }
    
        ~ThreadPool()
        {
            {
                std::unique_lock<std::mutex> lock(mutex_);
                stop_ = true;
            }
            condition_.notify_all();
    
            for (std::thread &thread : threads_)
            {
                thread.join();
            }
        }
    
        void Enqueue(std::function<void()> func)
        {
            {
                std::unique_lock<std::mutex> lock(mutex_);
                tasks_.emplace(std::move(func));
            }
            condition_.notify_one();
        }
    
    private:
        std::vector<std::thread> threads_;
        std::queue<std::function<void()>> tasks_;
    
        std::mutex mutex_;
        std::condition_variable condition_;
        bool stop_ = false;
    };
    
    class Reactor
    {
    public:
        Reactor(ThreadPool &threadPool) : threadPool_(threadPool)
        {
        }
    
        void Register(int clientSocket)
        {
            std::cout << "Register " << std::endl;
            //std::lock_guard lock(mutex_);
            std::cout << "Register2 " << std::endl;
            clientSockets_.push_back(clientSocket);
            std::cout << "Socket " << clientSocket << " registered." << std::endl;
        }
    
        void Remove(int clientSocket)
        {
            std::lock_guard<std::mutex> lock(mutex_);
            clientSockets_.erase(std::remove_if(clientSockets_.begin(), clientSockets_.end(),
                                                [clientSocket](int socket)
                                                { return socket == clientSocket; }),
                                 clientSockets_.end());
            close(clientSocket);
            FD_CLR(clientSocket, &readFds);
            std::cout << "Socket " << clientSocket << " removed." << std::endl;
            clientSocket = 0;
        }
    
        void Run(int mainSocket)
        {
            int maxFd = mainSocket;
    
            while (true)
            {
                FD_ZERO(&readFds);
                FD_SET(mainSocket, &readFds);
    
                {
                    std::unique_lock<std::mutex> lock(mutex_);
    
                    for (int socket : clientSockets_)
                    {
                        if (socket > 0)
                        {
                            FD_SET(socket, &readFds);
                            maxFd = std::max(maxFd, socket);
                        }
                    }
    
                    struct timeval timeout;
                    timeout.tv_sec = 0;
                    timeout.tv_usec = 0.01;
    
                    int selectResult = select(maxFd + 1, &readFds, nullptr, nullptr, &timeout);
                    if (selectResult == -1)
                    {
                        perror("select");
                        return;
                    }
                    else if (selectResult == 0)
                    {
                        // 没有就绪套接字,继续事件循环
                        continue;
                    }
    
                    if (FD_ISSET(mainSocket, &readFds))
                    {
                        // 有新的连接请求
                        struct sockaddr_in clientAddress;
                        socklen_t clientAddressLength = sizeof(clientAddress);
                        int clientSocket = accept(mainSocket, (struct sockaddr *)&clientAddress, &clientAddressLength);
    
                        if (clientSocket == -1)
                        {
                            if (errno == EWOULDBLOCK)
                            {
                                // 没有新连接,继续事件循环
                                continue;
                            }
                            else
                            {
                                perror("accept");
                                break;
                            }
                        }
                        else
                        {
                            std::cout << "Accepted new connection." << std::endl;
    
                            // 将客户端套接字添加到客户端套接字数组
    
                            Register(clientSocket);
                            std::cout << "Register1 " << std::endl;
                        }
                    }
    
                    // for (int i = 0; i < MAX_CLIENTS; ++i)
                    // {
                    //     if (FD_ISSET(clientSockets[i], &readFds))
                    //     {
                    //         readySockets.push_back(clientSockets[i]);
                    //     }
                    // }
                }
    
                for (int socket : clientSockets_)
                {
                    if (FD_ISSET(socket, &readFds))
                    {
                        threadPool_.Enqueue([this, socket]()
                                            {
                        EventData eventData;
                        eventData.clientSocket = socket;
                        ProcessEvent(eventData); });
                    }
                }
            }
        }
    
    private:
        void ProcessEvent(EventData eventData)
        {
            // 处理事件,这里只是简单示例,回传客户端的数据
            char buffer[BUFFER_SIZE];
            memset(buffer, 0, sizeof(BUFFER_SIZE));
            ssize_t bytesRead = recv(eventData.clientSocket, buffer, BUFFER_SIZE, 0);
            if (bytesRead > 0)
            {
                send(eventData.clientSocket, buffer, bytesRead, 0);
            }
            else if (bytesRead == 0 || (bytesRead == -1 && errno != EWOULDBLOCK))
            {
                // 连接关闭或出错,移除客户端
                Remove(eventData.clientSocket);
            }
            // 通知事件已处理
            std::cout << "Processed socket " << eventData.clientSocket << "  event data " << buffer << "in Thread: " << std::this_thread::get_id() << std::endl;
        }
    
    private:
        ThreadPool &threadPool_;
        std::mutex mutex_;
        std::vector<int> clientSockets_;
        fd_set readFds;
    };
    
    class Server
    {
    public:
        Server(ThreadPool &threadPool) : reactor_(threadPool)
        {
        }
    
        bool Init(int port)
        {
            mainSocket_ = socket(AF_INET, SOCK_STREAM, 0);
            if (mainSocket_ == -1)
            {
                std::cerr << "creat socket err" << std::endl;
                return false;
            }
    
            int opt = 1;
            if (setsockopt(mainSocket_, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) == -1)
            {
                std::cerr << "setsockopt err" << std::endl;
                close(mainSocket_);
                return false;
            }
    
            int flags = fcntl(mainSocket_, F_GETFL, 0);
            if (flags == -1)
            {
                std::cerr << "Error getting socket flags." << std::endl;
                close(mainSocket_);
                return false;
            }
            if (fcntl(mainSocket_, F_SETFL, flags | O_NONBLOCK) == -1)
            {
                std::cerr << "Error setting socket to non-blocking mode." << std::endl;
                close(mainSocket_);
                return false;
            }
    
            struct sockaddr_in serverAddress;
            serverAddress.sin_family = AF_INET;
            serverAddress.sin_addr.s_addr = INADDR_ANY;
            serverAddress.sin_port = htons(port);
    
            if (bind(mainSocket_, (struct sockaddr *)&serverAddress, sizeof(serverAddress)) == -1)
            {
                perror("bind");
                return false;
            }
    
            if (listen(mainSocket_, MAX_CLIENTS) == -1)
            {
                perror("listen");
                return false;
            }
    
            port_ = port;
    
            std::cout << "server init ok, listening on port: " << port_ << "。" << std::endl;
    
            return true;
        }
    
        void Run()
        {
            std::thread reactorThread([&]()
                                      { reactor_.Run(mainSocket_); });
    
            // 等待Reactor线程结束
            reactorThread.join();
        }
    
    private:
        int mainSocket_;
        int port_;
        Reactor reactor_;
    };
    
    int main(int argc, char *argv[])
    {
        if (argc < 2)
        {
            std::cerr << "please input the port of server。" << std::endl;
            return -1;
        }
    
        int port = atoi(argv[1]);
        ThreadPool threadPool(MAX_THREADS); // 创建线程池
        Server server(threadPool);          // 将线程池传递给服务器构造函数
    
        if (!server.Init(port))
        {
            std::cerr << "int server failed :" << port << std::endl;
            return 1;
        }
    
        server.Run();
    
        return 0;
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233
    • 234
    • 235
    • 236
    • 237
    • 238
    • 239
    • 240
    • 241
    • 242
    • 243
    • 244
    • 245
    • 246
    • 247
    • 248
    • 249
    • 250
    • 251
    • 252
    • 253
    • 254
    • 255
    • 256
    • 257
    • 258
    • 259
    • 260
    • 261
    • 262
    • 263
    • 264
    • 265
    • 266
    • 267
    • 268
    • 269
    • 270
    • 271
    • 272
    • 273
    • 274
    • 275
    • 276
    • 277
    • 278
    • 279
    • 280
    • 281
    • 282
    • 283
    • 284
    • 285
    • 286
    • 287
    • 288
    • 289
    • 290
    • 291
    • 292
    • 293
    • 294
    • 295
    • 296
    • 297
    • 298
    • 299
    • 300
    • 301
    • 302
    • 303
    • 304
    • 305
    • 306
    • 307
    • 308
    • 309
    • 310
    • 311
    • 312
    • 313
    • 314
    • 315
    • 316
    • 317
    • 318
    • 319
    • 320
    • 321
    • 322
    • 323
    • 324
    • 325
    • 326
    • 327
    • 328
    • 329
    • 330
    • 331
    • 调试: Linux下nc命令作为客户端:
      nc 127.0.0.1 7777
  • 相关阅读:
    2022国赛数模A题思路以及解析(附源码 可供学习训练使用)
    Bootstrap5 表格
    Linux单例模式
    128-Vue中的事件修饰符
    【Unity3D】ASE制作天空盒
    MySQL笔记总结
    零基础入门JavaWeb——正则表达式
    微信小程序显示流格式照片
    拦截|篡改|伪造.NET类库中不限于public的类和方法
    使用 Google Breakpad 来助力解决程序崩溃
  • 原文地址:https://blog.csdn.net/c1724136570/article/details/132643729