【C/C++】实现Reactor高并发服务器 完整版

在这里插入图片描述
代码结构 文件介绍

InetAddress.h
InetAddress类 ip和端口设置

Socket.h
Socket类 设置fd

Epoll.h
epollfd 管理类

Channel.h
Channel类 管理epoll以及对应回调函数实现

EventLoop.h
EventLoop事件循环类

TcpServer.h
服务器类

tcpepoll.cpp 主函数

InetAddress.h

#ifndef _INETADDRESS_H
#define _INETADDRESS_H#pragma on_INETADDRESS_He#include <string>
#include <arpa/inet.h>
#include <netinet/in.h>class InetAddress
{
private:sockaddr_in addr_;
public:InetAddress(const std::string &ip, uint16_t port);InetAddress(const sockaddr_in addr);InetAddress();~InetAddress();const char *ip()const;uint16_t port()const;const sockaddr *addr()const;void setaddr(sockaddr_in clientaddr);
};#endif // _INETADDRESS_H

InetAddress.cpp

#include "InetAddress.h"InetAddress::InetAddress()
{}InetAddress::InetAddress(const std::string &ip, uint16_t port)
{addr_.sin_family = AF_INET;addr_.sin_addr.s_addr = inet_addr(ip.c_str());addr_.sin_port = htons(port);
}InetAddress::InetAddress(const sockaddr_in addr):addr_(addr)
{}InetAddress::~InetAddress()
{}const char* InetAddress::ip()const
{return inet_ntoa(addr_.sin_addr);
}
uint16_t InetAddress::port()const
{return ntohs(addr_.sin_port);
}
const sockaddr* InetAddress::addr()const
{return (sockaddr*)&addr_;
}void InetAddress::setaddr(sockaddr_in clientaddr)
{addr_ = clientaddr;
}

Socket.h

#ifndef SOCKET_H
#define SOCKET_H#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <sys/fcntl.h>
#include <sys/epoll.h>
#include <netinet/tcp.h>  // TCP_NODELAY#include "InetAddress.h"int createnonblocking();class Socket
{
public:Socket(int fd);~Socket();int fd() const;void setreuseaddr(bool on);void setreuseport(bool on);void settcpnodelay(bool on);void setkeepalive(bool on);void bind(const InetAddress &servaddr);void listen(int n=128);int accept(InetAddress &clientaddr);private:const int fd_;
};#endif // !SOCKET_H

Socket.cpp

#include "Socket.h"int createnonblocking()
{int listenfd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, IPPROTO_TCP);if(listenfd < 0){perror("socket() failed"); exit(-1);}  return listenfd;
}Socket::Socket(int fd):fd_(fd)
{}
Socket::~Socket()
{close(fd_);
}int Socket::fd() const
{return fd_;
}
void Socket::setreuseaddr(bool on)
{int optval = on ? 1 : 0;setsockopt(fd_,  SOL_SOCKET, SO_REUSEADDR, &optval, static_cast<socklen_t>(sizeof(optval)));
}
void Socket::setreuseport(bool on)
{int optval = on ? 1 : 0;setsockopt(fd_,  SOL_SOCKET, SO_REUSEPORT, &optval, static_cast<socklen_t>(sizeof(optval)));
}
void Socket::settcpnodelay(bool on)
{int optval = on ? 1 : 0;setsockopt(fd_,  SOL_SOCKET, TCP_NODELAY, &optval, static_cast<socklen_t>(sizeof(optval)));    
}
void Socket::setkeepalive(bool on)
{int optval = on ? 1 : 0;setsockopt(fd_,  SOL_SOCKET, SO_KEEPALIVE, &optval, static_cast<socklen_t>(sizeof(optval)));    
}
void Socket::bind(const InetAddress &servaddr)
{if(::bind(fd_, servaddr.addr(), sizeof(sockaddr)) < 0){perror("bind() failed"); close(fd_); exit(-1);}
}
void Socket::listen(int n)
{if(::listen(fd_, n) != 0){perror("listen() failed");close(fd_);exit(-1);}
}
int Socket::accept(InetAddress &clientaddr)
{struct sockaddr_in peeraddr;socklen_t len = sizeof(peeraddr);int clientfd = accept4(fd_, (struct sockaddr*)&clientaddr, &len, SOCK_NONBLOCK);clientaddr.setaddr(peeraddr);return clientfd;
}

Epoll.h

#pragma once
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <sys/fcntl.h>
#include <sys/epoll.h>
#include <netinet/tcp.h>  // TCP_NODELAY
#include <vector>
#include "Channel.h"class Channel;class Epoll
{private:static const int MaxEvents = 100;int epollfd_;epoll_event events_[MaxEvents];public:Epoll();~Epoll();//void addfd(int fd, uint32_t op);void updatechannel(Channel *ch);//std::vector<epoll_event> loop(int timeout=-1);std::vector<Channel*> loop(int timeout=-1);
};

Epoll.cpp

#include "Epoll.h"/*
class Epoll
{private:static const int MaxEvents = 100;int epollfd;epoll_event events_[MaxEvents];public:Epoll();~Epoll();void addfd(int fd, uint32_t op);std::vector<epoll_event> loop(int timeout=-1);
}
*/Epoll::Epoll()
{if((epollfd_ = epoll_create(1)) == -1){printf("epoll_create() failed(%d).\n", errno);exit(-1);}
}
Epoll::~Epoll()
{close(epollfd_);
}
/*
void Epoll::addfd(int fd, uint32_t op)
{struct epoll_event ev;ev.data.fd = fd;ev.events = op; //水平if(epoll_ctl(epollfd_, EPOLL_CTL_ADD, fd, &ev) == -1){printf("epoll_ctl() failed(%d).\n", errno);exit(-1);        }
}
*/void Epoll::updatechannel(Channel *ch)
{epoll_event ev;ev.data.ptr = ch;ev.events = ch->events();if(ch->inpoll()){if(epoll_ctl(epollfd_, EPOLL_CTL_MOD, ch->fd(),&ev) == -1){printf("epoll_ctl() failed(%d).\n", errno);exit(-1);  }printf("epoll_ctl() EPOLL_CTL_MOD success. %d\n", ch->fd());}else{if(epoll_ctl(epollfd_, EPOLL_CTL_ADD, ch->fd(),&ev) == -1){printf("epoll_ctl() failed(%d).\n", errno);exit(-1);  }ch->setinepoll();printf("epoll_ctl() EPOLL_CTL_ADD success. %d\n", ch->fd());}  
}/*
std::vector<epoll_event> Epoll::loop(int timeout)
{std::vector<epoll_event> evs;bzero(events_, sizeof(events_));int infds = epoll_wait(epollfd_, events_, MaxEvents, timeout);if(infds < 0){perror("epoll_wait() failed "); exit(-1);}if(infds == 0){perror("epoll_wait() timeout \n"); return evs;}for(int i = 0; i < infds; i++){evs.push_back(events_[i]);}return evs;
}*/std::vector<Channel*> Epoll::loop(int timeout)
{std::vector<Channel*> channles;bzero(events_, sizeof(events_));int infds = epoll_wait(epollfd_, events_, MaxEvents, timeout);if(infds < 0){perror("epoll_wait() failed "); exit(-1);}if(infds == 0){perror("epoll_wait() timeout \n"); return channles;}for(int i = 0; i < infds; i++){Channel *ch = (Channel*)events_[i].data.ptr;    ch->setrevents(events_[i].events);channles.push_back(ch);}return channles;
}

Channel.h

#ifndef  CHANNEL_H
#define  CHANNEL_H#pragma once
#include <sys/epoll.h>
#include <functional>#include "Epoll.h"
#include "InetAddress.h"
#include "Socket.h"class Epoll;class Channel
{private:int fd_=-1;Epoll *ep_ = nullptr; //channle 对应的红黑树bool inepoll_=false; // epoll_ctl add moduint32_t events_=0;  //fd_需要监视的事件uint32_t revents_=0; //fd 已发生的事件std::function<void()> readcallback_;public:Channel(Epoll *ep, int fd);~Channel();int fd();void useet(); //采用边缘触发void enablereading(); //让epoll_wait()监视fd_的读事件void setinepoll();void setrevents(uint32_t ev);bool inpoll();uint32_t events();uint32_t revents(); //返回revents_成员void handleevent();void newconnection(Socket* servsock);void onmessage();void setreadcallback(std::function<void()> fn);
};#endif // ! CHANNEL_H

Channel.cpp

#include "Channel.h"/*
class Channel
{private:int fd_=-1;Epoll *ep_ = nullptr; //channle 对应的红黑树bool inepoll_=false; // epoll_ctl add moduint32_t events_=0;  //fd_需要监视的事件uint32_t revents_0; //fd 已发生的事件public:Channel(Epoll *ep, intfd);~Channel();int fd();void useet(); //采用边缘触发void enablereading(); //让epoll_wait()监视fd_的读事件void setinepoll();void setrevents(uint32_t ev);bool inpoll();uint32_t events();uint32_t revents(); //返回revents_成员
};*/Channel::Channel(Epoll *ep, int fd):ep_(ep),fd_(fd)
{}Channel::~Channel()
{
//在析构函数中,不要销毁ep_ 也不能关闭fd_ 不属于channel类
}int Channel::fd()
{return fd_;
}
void Channel::useet()
{events_ = events_ | EPOLLET;
}
void Channel::enablereading()
{events_ |= EPOLLIN;ep_->updatechannel(this);
}
void Channel::setinepoll()
{inepoll_ = true;
}
void Channel::setrevents(uint32_t ev)
{revents_= ev;
}
bool Channel::inpoll()
{return inepoll_;
}
uint32_t Channel::events()
{return events_;
}
uint32_t Channel::revents()
{return revents_;
}//事件处理函数, epoll_wait返回的时候执行它。
void Channel::handleevent()
{if(revents_ & EPOLLRDHUP){printf("cilent fd =%d disconnection\n", fd_);close(fd_);} else if (revents_ & EPOLLIN|EPOLLPRI){readcallback_();}else if (revents_ & EPOLLOUT){}else{printf("cilent fd =%d\n", fd_);close(fd_);}  
}void Channel::newconnection(Socket* servsock)
{InetAddress clientaddr;Socket *clientsock = new Socket(servsock->accept(clientaddr));printf("FILE(%s)FUNCTION(%s)LINE(%d) accept client fd=%d, ip=%s,port=%d ok.\n",__FILE__, __func__, __LINE__,clientsock->fd(), clientaddr.ip(), clientaddr.port());Channel *clientchannel = new Channel(ep_, clientsock->fd());clientchannel->setreadcallback(std::bind(&Channel::onmessage, clientchannel));clientchannel->useet();clientchannel->enablereading();
}void Channel::onmessage()
{char buffer[1024];memset(buffer, 0, sizeof(buffer));size_t nread = recv(fd_, buffer, sizeof(buffer), 0);if(nread > 0){printf("tcpepoll Recv:%s\n", buffer);send(fd_, buffer, strlen(buffer), 0);}else if (nread == -1 && errno == EINTR){}else if(nread == -1 && ((errno == EAGAIN) || (errno == EWOULDBLOCK))){}else if (nread == 0){printf("clientfd:%d disconnected\n", fd_);close(fd_);}
}//设置fd的回调函数
void Channel::setreadcallback(std::function<void()> fn)
{readcallback_ = fn;
}

EventLoop.h

#pragma once#include "Epoll.h"class EventLoop
{
private:Epoll *ep_;
public:EventLoop();~EventLoop();void run();Epoll* ep();
};

EventLoop.cpp

#include "EventLoop.h"/*
class EventLoop
{
private:Epoll *ep_;
public:EventLoop();~EventLoop();void run();
};
*/EventLoop::EventLoop():ep_(new Epoll)
{}EventLoop::~EventLoop()
{delete ep_;
}void EventLoop::run()
{while(true){std::vector<Channel*> channles = ep_->loop();for(auto &ch:channles){ch->handleevent();}}
}Epoll* EventLoop::ep()
{return ep_;
}

TcpServer.h

#pragma once#include "EventLoop.h"
#include "Socket.h"
#include "Channel.h"class TcpServer
{
private:EventLoop loop_;
public:TcpServer(const std::string &ip, const uint16_t port);~TcpServer();void start();
};

TcpServer.cpp

#include "TcpServer.h"/*
class TcpServer
{
private:EventLoop loop_;
public:TcpServer(const std::string &ip, const uint16_t port);~TcpServer();
};
*/TcpServer::TcpServer(const std::string &ip, const uint16_t port)
{Socket *servsock = new Socket(createnonblocking());InetAddress servaddr(ip, port);servsock->setreuseaddr(true);servsock->setreuseport(true);servsock->settcpnodelay(true);servsock->setkeepalive(true);servsock->bind(servaddr);servsock->listen();Channel *servchannel = new Channel(loop_.ep(), servsock->fd());servchannel->setreadcallback(std::bind(&Channel::newconnection, servchannel, servsock));servchannel->enablereading();
}TcpServer::~TcpServer()
{}void TcpServer::start()
{loop_.run();
}

tcpepoll.cpp

#include "TcpServer.h"int main(int argc, char *argv[])
{if(argc !=3){printf("usage: ./tcpepoll ip port\n");printf("examples ./tcpepoll 127.0.0.1 6666\n");return -1;}TcpServer tcpserver(argv[1], atoi(argv[2]));tcpserver.start(); //运行事件循环return 0;
} 

client.cpp

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <sys/fcntl.h>
#include <sys/epoll.h>
#include <netinet/tcp.h>  // TCP_NODELAY
#include <time.h>int main(int argc, char *argv[])
{if(argc !=3){printf("usage: ./client ip port");return -1;}int sockfd;struct sockaddr_in servaddr;char buf[1024];if((sockfd=socket(AF_INET,SOCK_STREAM, 0)) < 0){return -1;}memset(&servaddr, 0, sizeof(servaddr));servaddr.sin_family = AF_INET;servaddr.sin_port = htons(atoi(argv[2]));if(connect(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr))!=0){return -1;}printf("connect ok\n");for(int i = 0; i < 200000; i++){memset(buf, 0, sizeof(buf));printf("please input:");scanf("%s", buf);if(send(sockfd, buf, strlen(buf), 0) < 0){close(sockfd);return -1;}memset(buf, 0, sizeof(buf));if(recv(sockfd, buf, sizeof(buf), 0) <= 0){return -1;}printf("i:%d recv:%s\n", i, buf);}return 0;
}

makefile

all: client tcpepollclient: client.cppg++ -g -o client client.cpp tcpepoll:tcpepoll.cpp InetAddress.cpp Socket.cpp Epoll.cpp Channel.cpp EventLoop.cpp TcpServer.cppg++  -g -o tcpepoll tcpepoll.cpp InetAddress.cpp Socket.cpp Epoll.cpp Channel.cpp EventLoop.cpp TcpServer.cppclean:rm -f client tcpepoll

运行

服务器
在这里插入图片描述
客户端
在这里插入图片描述
在这里插入图片描述

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

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Linux用到的命令

1 压缩文件 tar -czf wonderful.tar.gz pm 这个命令的作用就是创建一个以.tar.gz结尾的包文件&#xff0c;然后调用gzip程序将当前目录下的pm文件夹压缩到这个以.tar.gz结尾的文件里面去

普中51单片机学习(二)

51单片机介绍 所需基础知识 基础数模电知识&#xff0c;简单的C语言。 PS&#xff1a;如果有不懂的直接通义千问。。。 什么是单片机 在一片集成电路芯片上集成微处理器、存储器、I/O接口电路&#xff0c;从而构成了单芯片微型计算机&#xff0c;即单片机。 学习方法 多实…

ActiveMQ高可用架构涉及常用功能整理

ActiveMQ高可用架构涉及常用功能整理 1. activemq的集群模式2. 镜像模式高可用系统架构和相关组件2.1 架构说明2.2 相关概念说明2.3 消息模型2.3.1 点对点2.3.2 发布订阅 3. activemq常用命令4. activemq配置集群5. 疑问和思考5.1 activemq的数据删除策略是怎样的&#xff1f;5…

医学生物化学与生物分子学试题及答案,分享几个实用搜题和学习工具 #经验分享#学习方法#其他

大学生的学习生活离不开一些实用的工具&#xff0c;它们能够帮助我们更高效地学习和管理时间。 1.大鱼搜题 这是一个公众号 包括教材课后习题&#xff0c;连冷门网课习题也能找到标准答案&#xff0c;日常练习和备考刷真题都离不开、 下方附上一些测试的试题及答案 1、仓储…

花费200元,我用全志H616和雪糕棒手搓了一台可UI交互的视觉循迹小车

常见的视觉循迹小车都具备有路径识别、轨迹跟踪、转向避障、自主决策等基本功能&#xff0c;如果不采用红外避障的方案&#xff0c;那么想要完全满足以上这些功能&#xff0c;摄像头、电机、传感器这类关键部件缺一不可&#xff0c;由此一来小车成本也就难以控制了。 但如果&a…

JavaWeb学习(1)数据库相关概念,mysql数据库管理系统,SQL语句

数据库相关概念 数据库&#xff1a; 存储数据的仓库&#xff0c;数据是有组织的进行存储 英文&#xff1a;DataBase 简称DB 数据库管理系统&#xff1a; 管理数据库的大型软件 英文&#xff1a;DataBase Management System,简称DBMS SQL 英文&#xff1a;Stry…

Java项目,营销抽奖系统设计实现

作者&#xff1a;小傅哥 博客&#xff1a;https://bugstack.cn 项目&#xff1a;https://gaga.plus 沉淀、分享、成长&#xff0c;让自己和他人都能有所收获&#xff01;&#x1f604; 大家好&#xff0c;我是技术UP主&#xff0c;小傅哥。 经过这个假期的嘎嘎卷&#x1f9e8;…

你真的了解—————NumPy吗

&#x1f308;个人主页&#xff1a;小田爱学编程 &#x1f525; 系列专栏&#xff1a;opencv &#x1f3c6;&#x1f3c6;关注博主&#xff0c;随时获取更多关于IT的优质内容&#xff01;&#x1f3c6;&#x1f3c6; &#x1f600;欢迎来到小田代码世界~ &#x1f601; 喜欢的…

深入探讨JMeter中不为人知的JSONPath用法

在jmeter使用过程中&#xff0c;我们经常会看到接口返回数据类型为application/json&#xff0c;也就时我们常说的json格式。 而在功能测试时&#xff0c;我们经常会要对它的结果进行断言&#xff0c;确认结果是否与预期一致&#xff0c;有时候还会想从结果中提取某个值&#…

VMware还原Windows11 ghost镜像

文章目录 环境步骤准备制作启动iso文件创建虚拟机启动虚拟机还原Windows 参考 环境 Windows 11 家庭中文版VMware Workstation 17 Pro石大师装机大师Windows 11 ghost系统镜像 步骤 准备 下载好Windows 11 ghost系统镜像&#xff0c;我下载的文件是 FQ_WIN11_X64_VDL_V2080…

sentinel的资源数据指标是如何采集

资源数据采集 之前的NodeSelectorSlot和ClusterBuilderSlot已经完成了对资源调用树的构建, 现在则是要对资源进行收集, 核心点就是这些资源数据是如何统计 LogSlot 作用: 记录异常请求日志, 用于故障排查 public class LogSlot extends AbstractLinkedProcessorSlot<Def…

Keepalived实现Nginx的高可用集群案例

服务器规划: serverb(nginx2):192.168.233.144 serverc(客户端):192.168.233.140 serverd(nginx1):192.168.233.141 结构图: serverd(nginx1): # 安装nginx yum install nginx -y# 进入nginx配置目录 cd /e…