基于多反应堆的高并发服务器【C/C++/Reactor】(中)在TcpConnection 中接收并解析Http请求消息

本文主要是介绍基于多反应堆的高并发服务器【C/C++/Reactor】(中)在TcpConnection 中接收并解析Http请求消息,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一、在TcpConnection 中多添加和http协议相关的request和response

struct TcpConnection {struct EventLoop* evLoop;struct Channel* channel;struct Buffer* readBuf;struct Buffer* writeBuf;char name[32];// http协议struct HttpRequest* request;struct HttpResponse* response;
};

二、给客户端回复数据(方法一)

1.在Buffer.h文件中添加bufferSendData函数:

// 发送数据
int bufferSendData(struct Buffer* buf,int socket);
// 发送数据
int bufferSendData(struct Buffer* buf,int socket) {// 判断有无数据int readableSize = bufferReadableSize(buf);// 这些未读的数据就是待发送的数据if(readableSize > 0) {int count = send(socket,buf->data + buf->readPos,readableSize,MSG_NOSIGNAL);if(count > 0) {buf->readPos += count;usleep(1);}return count;}    return 0;
}

 2.在TcpConnection.c文件中添加processWrite函数:

int processWrite(void* arg) {struct TcpConnection* conn = (struct TcpConnection*)arg;// 发送数据int count = bufferSendData(conn->writeBuf,conn->channel->fd);if(count > 0) {// 判断数据是否被全部发送出去了if(bufferReadableSize(conn->writeBuf) == 0){// 1.不再检测写事件 -- 修改channel中保存的事件writeEventEnable(conn->channel,false);// 2.修改dispatcher检测的集合 -- 添加任务节点eventLoopAddTask(conn->evLoop,conn->channel,MODIFY);    // 3.删除这个节点eventLoopAddTask(conn->evLoop,conn->channel,DELETE);}}return 0;
}

3.修改tcpConnectionInit函数中调用的channelInit函数的写回调函数为processWrite函数

​// 初始化
struct TcpConnection* tcpConnectionInit(int fd,struct EventLoop* evLoop) {struct TcpConnection* conn = (struct TcpConnection*)malloc(sizeof(struct TcpConnection));conn->evLoop = evLoop;struct Channel* channel = channelInit(fd,ReadEvent,processRead,processWrite,tcpConnectionDestroy,conn);conn->channel = channel;conn->readBuf = bufferInit(10240); // 10kconn->writeBuf = bufferInit(10240); // 10ksprintf(conn->name,"TcpConnection-%d",fd);// http协议conn->request = httpRequestInit();conn->response = httpResponseInit();// 把channel添加到事件循环对应的任务队列里边eventLoopAddTask(evLoop,conn->channel,ADD);return conn;
}

三、给客户端回复数据(方法二)

  • 在TcpConnection.h中添加 
// #define MSG_SEND_AUTO
  • TcpConnection.c
// 接收客户端数据
int processRead(void* arg) {struct TcpConnection* conn = (struct TcpConnection*)arg;// 接收数据int count = bufferSocketRead(conn->readBuf,conn->channel->fd);if(count > 0) {// 接收到了Http请求,解析Http请求int socket = conn->channel->fd;
#ifdef MSG_SEND_AUTO  // 给客户端回复数据的方式一writeEventEnable(conn->channel,true);eventLoopAddTask(conn->evLoop,conn->channel,MODIFY);
#endifbool flag = parseHttpRequest(conn->request,conn->readBuf,conn->response,conn->writeBuf,socket);if(!flag) {// 解析失败,回复一个简单的htmlchar* errMsg = "Http/1.1 400 Bad Request\r\n\r\n";bufferAppendString(conn->writeBuf,errMsg);}}else{
#ifdef MSG_SEND_AUTO// 断开连接eventLoopAddTask(conn->evLoop,conn->channel,DELETE);
#endif}
#ifndef MSG_SEND_AUTO// 断开连接eventLoopAddTask(conn->evLoop,conn->channel,DELETE);
#endifreturn 0;
}

1.修改HttpRequest.c文件中的sendFile函数和sendDir函数

void sendFile(const char* fileName,struct Buffer* sendBuf,int cfd) {// 打开文件int fd = open(fileName,O_RDONLY);if(fd < 0) {perror("open");return;}// assert(fd > 0); 
#if 1while (1) {char buf[1024];int len = read(fd,buf,sizeof(buf));if(len > 0) {// send(cfd,buf,len,0);bufferAppendData(sendBuf,buf,len);
#ifndef MSG_SEND_AUTO // 给客户端回复数据(方法二)bufferSendData(sendBuf,cfd);
#endif}else if(len == 0) {break;}else{close(fd);perror("read");}}
#else// 把文件内容发送给客户端off_t offset = 0;int size = lseek(fd,0,SEEK_END);// 文件指针移动到了尾部lseek(fd,0,SEEK_SET);// 移动到文件头部while (offset < size){int ret = sendfile(cfd,fd,&offset,size - offset);printf("ret value: %d\n",ret);if (ret == -1 && errno == EAGAIN) {printf("没数据...\n");}}
#endifclose(fd);
}void sendDir(const char* dirName,struct Buffer* sendBuf,int cfd) {char buf[4096] = {0};sprintf(buf,"<html><head><title>%s</title></head><body><table>",dirName);struct dirent** nameList;int num = scandir(dirName,&nameList,NULL,alphasort);for(int i=0;i<num;i++) {// 取出文件名 nameList 指向的是一个指针数组 struct dirent* tmp[]char* name = nameList[i]->d_name;struct stat st;char subPath[1024] = {0};sprintf(subPath,"%s/%s",dirName,name);stat(subPath,&st);if(S_ISDIR(st.st_mode)) {// 从当前目录跳到子目录里边,/sprintf(buf+strlen(buf),"<tr><td><a href=\"%s/\">%s</a></td><td>%ld</td></tr>",name,name,st.st_size);}else{sprintf(buf+strlen(buf),"<tr><td><a href=\"%s\">%s</a></td><td>%ld</td></tr>",name,name,st.st_size);}// send(cfd,buf,strlen(buf),0);bufferAppendString(sendBuf,buf);
#ifndef MSG_SEND_AUTO // 给客户端回复数据(方法二)bufferSendData(sendBuf,cfd);
#endifmemset(buf,0,sizeof(buf));free(nameList[i]); } sprintf(buf,"</table></body></html>");// send(cfd,buf,strlen(buf),0);bufferAppendString(sendBuf,buf);
#ifndef MSG_SEND_AUTO // 给客户端回复数据(方法二)bufferSendData(sendBuf,cfd);
#endiffree(nameList);
}

2.修改HttpResponse.c文件的httpResponsePrepareMsg函数

// 组织http响应数据
void httpResponsePrepareMsg(struct HttpResponse* response,struct Buffer* sendBuf,int socket) {// 状态行char tmp[1024] = {0};sprintf(tmp,"HTTP/1.1 %d %s\r\n",response->statusCode,response->statusMsg);bufferAppendString(sendBuf,tmp);// 响应头for(int i=0;i<response->headerNum;++i) {// memset(tmp,0,sizeof(tmp));  ?????????sprintf(tmp,"%s: %s\r\n",response->headers[i].key,response->headers[i].value);bufferAppendString(sendBuf,tmp);}// 空行bufferAppendString(sendBuf,"\r\n");#ifndef MSG_SEND_AUTO // 给客户端回复数据(方法二)bufferSendData(sendBuf,socket);
#endif// 回复的数据response->sendDataFunc(response->fileName,sendBuf,socket);
}

 四、释放资源 tcpConnectionDestroy

// 释放资源
int tcpConnectionDestroy(void* arg);
// 释放资源
int tcpConnectionDestroy(void* arg) {struct TcpConnection* conn = (struct TcpConnection*)arg;if(conn!=NULL) {if (conn->readBuf && bufferReadableSize(conn->readBuf) == 0 &&conn->writeBuf && bufferReadableSize(conn->writeBuf) == 0) {destroyChannel(conn->evLoop,conn->channel);bufferDestroy(conn->readBuf);bufferDestroy(conn->writeBuf);httpRequestDestroy(conn->request);httpResponseDestroy(conn->response);free(conn);}}return 0;
}

五、日志功能

#pragma once
#include <stdarg.h>
#include <stdio.h>#define  DEBUG   1  #if DEBUG
/*
*  如果不加 do ... while(0) 在进行条件判断的时候(只有一句话), 省略了{}, 就会出现语法错误
*  if 
*     xxxxx
*  else
*     xxxxx
*  宏被替换之后, 在 else 前面会出现一个 ;  --> 语法错误
*/
#define LOG(type, fmt, args...)  \do{\printf("%s: %s@%s, line: %d\n***LogInfo[", type, __FILE__, __FUNCTION__, __LINE__);\printf(fmt, ##args);\printf("]\n\n");\}while(0)
#define Debug(fmt, args...) LOG("DEBUG", fmt, ##args)
#define Error(fmt, args...) do{LOG("ERROR", fmt, ##args);exit(0);}while(0)
#else
#define LOG(fmt, args...)  
#define Debug(fmt, args...)
#define Error(fmt, args...)
#endif

 

这篇关于基于多反应堆的高并发服务器【C/C++/Reactor】(中)在TcpConnection 中接收并解析Http请求消息的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/597710

相关文章

网页解析 lxml 库--实战

lxml库使用流程 lxml 是 Python 的第三方解析库,完全使用 Python 语言编写,它对 XPath表达式提供了良好的支 持,因此能够了高效地解析 HTML/XML 文档。本节讲解如何通过 lxml 库解析 HTML 文档。 pip install lxml lxm| 库提供了一个 etree 模块,该模块专门用来解析 HTML/XML 文档,下面来介绍一下 lxml 库

服务器集群同步时间手记

1.时间服务器配置(必须root用户) (1)检查ntp是否安装 [root@node1 桌面]# rpm -qa|grep ntpntp-4.2.6p5-10.el6.centos.x86_64fontpackages-filesystem-1.41-1.1.el6.noarchntpdate-4.2.6p5-10.el6.centos.x86_64 (2)修改ntp配置文件 [r

【C++ Primer Plus习题】13.4

大家好,这里是国中之林! ❥前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站。有兴趣的可以点点进去看看← 问题: 解答: main.cpp #include <iostream>#include "port.h"int main() {Port p1;Port p2("Abc", "Bcc", 30);std::cout <<

C++包装器

包装器 在 C++ 中,“包装器”通常指的是一种设计模式或编程技巧,用于封装其他代码或对象,使其更易于使用、管理或扩展。包装器的概念在编程中非常普遍,可以用于函数、类、库等多个方面。下面是几个常见的 “包装器” 类型: 1. 函数包装器 函数包装器用于封装一个或多个函数,使其接口更统一或更便于调用。例如,std::function 是一个通用的函数包装器,它可以存储任意可调用对象(函数、函数

C++11第三弹:lambda表达式 | 新的类功能 | 模板的可变参数

🌈个人主页: 南桥几晴秋 🌈C++专栏: 南桥谈C++ 🌈C语言专栏: C语言学习系列 🌈Linux学习专栏: 南桥谈Linux 🌈数据结构学习专栏: 数据结构杂谈 🌈数据库学习专栏: 南桥谈MySQL 🌈Qt学习专栏: 南桥谈Qt 🌈菜鸡代码练习: 练习随想记录 🌈git学习: 南桥谈Git 🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈�

【C++】_list常用方法解析及模拟实现

相信自己的力量,只要对自己始终保持信心,尽自己最大努力去完成任何事,就算事情最终结果是失败了,努力了也不留遗憾。💓💓💓 目录   ✨说在前面 🍋知识点一:什么是list? •🌰1.list的定义 •🌰2.list的基本特性 •🌰3.常用接口介绍 🍋知识点二:list常用接口 •🌰1.默认成员函数 🔥构造函数(⭐) 🔥析构函数 •🌰2.list对象

06 C++Lambda表达式

lambda表达式的定义 没有显式模版形参的lambda表达式 [捕获] 前属性 (形参列表) 说明符 异常 后属性 尾随类型 约束 {函数体} 有显式模版形参的lambda表达式 [捕获] <模版形参> 模版约束 前属性 (形参列表) 说明符 异常 后属性 尾随类型 约束 {函数体} 含义 捕获:包含零个或者多个捕获符的逗号分隔列表 模板形参:用于泛型lambda提供个模板形参的名

6.1.数据结构-c/c++堆详解下篇(堆排序,TopK问题)

上篇:6.1.数据结构-c/c++模拟实现堆上篇(向下,上调整算法,建堆,增删数据)-CSDN博客 本章重点 1.使用堆来完成堆排序 2.使用堆解决TopK问题 目录 一.堆排序 1.1 思路 1.2 代码 1.3 简单测试 二.TopK问题 2.1 思路(求最小): 2.2 C语言代码(手写堆) 2.3 C++代码(使用优先级队列 priority_queue)

高并发环境中保持幂等性

在高并发环境中保持幂等性是一项重要的挑战。幂等性指的是无论操作执行多少次,其效果都是相同的。确保操作的幂等性可以避免重复执行带来的副作用。以下是一些保持幂等性的常用方法: 唯一标识符: 请求唯一标识:在每次请求中引入唯一标识符(如 UUID 或者生成的唯一 ID),在处理请求时,系统可以检查这个标识符是否已经处理过,如果是,则忽略重复请求。幂等键(Idempotency Key):客户端在每次

BUUCTF靶场[web][极客大挑战 2019]Http、[HCTF 2018]admin

目录   [web][极客大挑战 2019]Http 考点:Referer协议、UA协议、X-Forwarded-For协议 [web][HCTF 2018]admin 考点:弱密码字典爆破 四种方法:   [web][极客大挑战 2019]Http 考点:Referer协议、UA协议、X-Forwarded-For协议 访问环境 老规矩,我们先查看源代码