epoll实现并发服务器

#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/epoll.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#define ERR_MSG(msg)                                       \
    do                                                     \
    {                                                      \
        printf("%s %s %d:", __FILE__, __func__, __LINE__); \
        perror(msg);                                       \
        return (-1);                                       \
    } while (0)

#define PORT 6666
#define IP "192.168.250.100"

int main(int argc, const char *argv[])
{
    // 创建流式套接字
    int sfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sfd < 0)
    {
        ERR_MSG("socket");
        return -1;
    }
    printf("sfd=%d __line__=%d \n", sfd, __LINE__);
    // 允许端口快速复用
    int reuse = 1;
    if (setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0)
    {
        ERR_MSG("setsockopt");
        return -1;
    }
    printf("setsockopt success\n");
    // 填充服务器信息
    struct sockaddr_in sin;
    sin.sin_family = AF_INET;
    sin.sin_port = htons(PORT);          // 端口号转网络字节序
    sin.sin_addr.s_addr = inet_addr(IP); // 服务器IP地址
    // 绑定套接字
    if (bind(sfd, (struct sockaddr *)&sin, sizeof(sin)) < 0)
    {
        ERR_MSG("bind");
        return -1;
    }
    printf("bind success __%d__\n", __LINE__);
    // 将套接字创建为被动监听模式
    if (listen(sfd, 128) < 0)
    {
        ERR_MSG("listen faile\n");
        return -1;
    }
    printf("listen success\n");

    /************epoll******************/
    struct epoll_event event;
    struct epoll_event events[10]; // 发生事件的文件描述符表
    char buf[128] = "";
    // 创建红黑树
    int epfd = epoll_create(1); // 填入大于0的数字
    if (epfd < 0)
    {
        printf("epoll_creat faile\n");
        return -1;
    }
    // 将要监听的文件描述符添加到epoll中
    event.events = EPOLLIN;
    event.data.fd = 0;                                   // 0号文件描述符,键盘
    int ret = epoll_ctl(epfd, EPOLL_CTL_ADD, 0, &event); // 添加
    if (ret)
    {
        printf("epoll_ctl faile \n");
        return -1;
    }
    event.events = EPOLLIN;
    event.data.fd = sfd;                               // 服务器文件描述符
    ret = epoll_ctl(epfd, EPOLL_CTL_ADD, sfd, &event); // 添加
    if (ret)
    {
        printf("epoll_ctl faile \n");
        return -1;
    }

    // 循环监听文件描述符表
    ssize_t rec;
    while (1)
    {
        ret = epoll_wait(epfd, events, 10, -1); // 等待epoll有文件描述符
        if (ret < 0)
        {
            printf("epoll_wait faile\n");
            return -1;
        }
        for (int i = 0; i < ret; i++)
        {
            // 发送
            if ((events[i].events & EPOLLIN) && (events[i].data.fd == 0))
            {
                bzero(buf, sizeof(buf));
                printf("输入事件\n");
                fgets(buf, sizeof(buf), stdin);
                buf[strlen(buf) - 1] = '\0';

                if (send(sfd, buf, sizeof(buf), 0) < 0)
                {
                    ERR_MSG("send faile");
                    return -1;
                }

                printf("发送成功\n");
            }

            // 接收
            if ((events[i].events & EPOLLIN) && (events[i].data.fd == sfd))
            {
                bzero(buf, sizeof(buf));
                rec = recv(sfd, buf, sizeof(buf), 0);
                if (rec < 0)
                {
                    ERR_MSG("recv faile");
                    return -1;
                }
                else if (0 == rec)
                {
                    printf("sfd=%d 服务器下线\n", sfd);
                    break;
                }
                printf("sfd=%d : %s __%d__ \n", sfd, buf, __LINE__);
            }
        }
    }
    close(sfd);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用epoll和线程池实现并发服务器的C++11代码示例: ```cpp #include <iostream> #include <thread> #include <vector> #include <queue> #include <mutex> #include <condition_variable> #include <sys/epoll.h> #include <unistd.h> #define MAX_EVENTS 100 #define THREAD_POOL_SIZE 10 std::mutex mtx; std::condition_variable cv; std::queue<int> taskQueue; void workerThread() { while (true) { std::unique_lock<std::mutex> lock(mtx); cv.wait(lock, [] { return !taskQueue.empty(); }); int fd = taskQueue.front(); taskQueue.pop(); // 处理任务,这里可以根据具体需求进行处理 lock.unlock(); // 继续监听其他事件 } } int main() { // 创建epoll句柄 int epoll_fd = epoll_create(1); if (epoll_fd == -1) { std::cerr << "Failed to create epoll" << std::endl; return 1; } // 创建线程池 std::vector<std::thread> threadPool; for (int i = 0; i < THREAD_POOL_SIZE; ++i) { threadPool.emplace_back(workerThread); } // 添加监听事件到epoll句柄 struct epoll_event event; event.events = EPOLLIN; event.data.fd = /* 监听的文件描述符 */; if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, /* 监听的文件描述符 */, &event) == -1) { std::cerr << "Failed to add event to epoll" << std::endl; return 1; } // 开始监听事件 struct epoll_event events[MAX_EVENTS]; while (true) { int num_events = epoll_wait(epoll_fd, events, MAX_EVENTS, -1); if (num_events == -1) { std::cerr << "Failed to wait for events" << std::endl; return 1; } for (int i = 0; i < num_events; ++i) { if (events[i].events & EPOLLIN) { // 处理读事件,将任务添加到任务队列 std::lock_guard<std::mutex> lock(mtx); taskQueue.push(events[i].data.fd); cv.notify_one(); } } } // 清理资源 close(epoll_fd); for (auto& thread : threadPool) { thread.join(); } return 0; } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值