一个基本的http客户端

高可用 客户端

1. httpClient.h

#include <iostream>
#include <string>
#include <functional>class HttpClient
{
public:HttpClient(std::string url) : url_(url), port_(0) {}int write_http(const std::string &method, const std::string &msg);private:int get_socket();int set_sock_timeout(int sockfd, int sec, int ms);int set_buf_size(int sockfd, int sendsize, int recvsize);int domain_judge(const char *buf);int split_url(std::string &url, std::string &host, unsigned short &port);int host_get_by_name(const char *name);void print_netstat(int err);int noblock_connect(int sockfd, struct sockaddr *addrs, int addrlen);int make_http_head(const char *method, std::string &httpmsg, const std::string &purl);int make_http_msg(const std::string &method, std::string &msg);int writen(int connfd, const char *vptr, size_t n);int recvn_timeout(int connfd, char *vptr, int n, int timeout);std::string readn(int sockfd, size_t n);int parse_recvmsg(std::string &recvmsg);int parse_test(std::string &msg);private:std::function<int(std::string &)> parseFunc_;std::string url_;std::string host_;unsigned short port_;
};

2.httpClient.cpp

#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <string>
#include <vector>
#include <memory>#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <netdb.h>
#include <unistd.h>
#include <sys/ioctl.h>#include <jsoncpp/json/json.h>#include "httpClient.h"int HttpClient::make_http_head(const char *method, std::string &httpmsg, const std::string &purl)
{char headbuf[1024] = {0};int len = snprintf(headbuf, sizeof(headbuf), "%s %s HTTP/1.1\r\n""Content-Type: application/json\r\n""Accept: application/json\r\n""Host: %s:%d\r\n""Connection: Keep-Alive\r\n""Content-Length: %d\r\n\r\n",method,purl.c_str(),host_.c_str(),port_,static_cast<int>(httpmsg.size()));httpmsg = headbuf + httpmsg;return 0;
}int HttpClient::make_http_msg(const std::string &method, std::string &msg)
{return make_http_head(method.c_str(), msg, "");
}int HttpClient::writen(int connfd, const char *vptr, size_t n)
{int nleft = n, nwrite = 0, retryCont = 0;char *ptr = const_cast<char *>(vptr);while (nleft > 0){if ((nwrite = send(connfd, ptr, nleft, MSG_NOSIGNAL)) <= 0){if (retryCont < 100 && (nwrite == 0 || errno == EINTR)){nwrite = 0;++retryCont;usleep(10000);}else{return -1;}}nleft -= nwrite;ptr += nwrite;}return n;
}int HttpClient::recvn_timeout(int connfd, char *vptr, int n, int sec)
{int nleft = n;int nread = 0, retryCnt = 0;char *ptr = vptr;fd_set fdset;struct timeval timeout;while (nleft > 0){timeout.tv_sec = sec;timeout.tv_usec = 0;FD_ZERO(&fdset);FD_SET(connfd, &fdset);if (select(connfd + 1, &fdset, nullptr, nullptr, &timeout) <= 0){printf("select fail errno = %d\n", errno);break;}if ((nread = recv(connfd, ptr, nleft, 0)) < 0){if (retryCnt < 50 && (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)){nread = 0;++retryCnt;usleep(10000);}else{break;}}else if (nread == 0){break;}nleft -= nread;ptr += nread;}return (n - nleft);
}std::string HttpClient::readn(int sockfd, size_t n)
{char buf[2048] = {0};std::string result;int total = 0;int byterecv;do{byterecv = recvn_timeout(sockfd, buf, 2048, 5);if (byterecv <= 0){break;}total += byterecv;result.append(buf, byterecv);} while (total < n && byterecv == sizeof(buf));return result;
}int HttpClient::parse_recvmsg(std::string &recvmsg)
{std::string ::size_type headend = recvmsg.find("\r\n\r\n");if (headend == std::string::npos){std::cout << "not found header" << std::endl;return false;}std::string body = recvmsg.substr(headend + 4);return parseFunc_(body);
}int HttpClient::split_url(std::string &url, std::string &host, unsigned short &port)
{if (!url.compare(0, 7, "http://")){url = url.substr(7);}if (!url.compare(0, 8, "https://")){url = url.substr(8);}size_t slashPos = url.find("/");if (slashPos != std::string::npos){url = url.substr(0, slashPos);}size_t colonPos = url.find(":");if (colonPos == std::string::npos){host = url;port = 80;}else{host = url.substr(0, colonPos);port = atoi(url.substr(colonPos + 1).c_str());}
}int HttpClient::domain_judge(const char *buf)
{if (nullptr == buf){return false;}bool hasChar = false, hasDot = false;for (size_t i = 0; i < strlen(buf); ++i){if (isalpha(buf[i])){hasChar = true;continue;}if ('.' == buf[i]){hasDot = true;continue;}if (hasChar && hasDot){return true;}}return false;
}int HttpClient::host_get_by_name(const char *name)
{//    char ipaadress[64] = {0};struct addrinfo hints, *reslut = nullptr, *address = nullptr;memset(&hints, 0, sizeof(addrinfo));hints.ai_family = AF_UNSPEC; // ipv4 ipv6hints.ai_flags = AI_PASSIVE;hints.ai_socktype = SOCK_STREAM;int ret = getaddrinfo(name, nullptr, &hints, &reslut);if (ret != 0){std::cerr << "getaddrinfo err " << gai_strerror(ret) << std::endl;return ret;}for (address = reslut; address != nullptr; address = address->ai_next){if (address->ai_family == AF_INET){struct sockaddr_in *addr = reinterpret_cast<struct sockaddr_in *>(address->ai_addr);freeaddrinfo(reslut);return static_cast<int>(addr->sin_addr.s_addr);}else if (address->ai_family == AF_INET6){struct sockaddr_in6 *addr = reinterpret_cast<struct sockaddr_in6 *>(address->ai_addr);continue; // 暂不使用ipv6}}freeaddrinfo(reslut);return false;
}int HttpClient::set_buf_size(int sockfd, int sendsize, int recvsize)
{int ret1 = ::setsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, reinterpret_cast<char *>(&sendsize), sizeof(sendsize));int ret2 = ::setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, reinterpret_cast<char *>(&recvsize), sizeof(recvsize));return (ret1 == 0 && ret2 == 0) ? 0 : -1;
}int HttpClient::set_sock_timeout(int sockfd, int sec, int ms)
{timeval timeout = {sec, ms * 1000};int ret1 = ::setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast<char *>(&timeout), sizeof(timeout));int ret2 = ::setsockopt(sockfd, SOL_SOCKET, SO_SNDTIMEO, reinterpret_cast<char *>(&timeout), sizeof(timeout));return (ret1 == 0 && ret2 == 0) ? 0 : -1;
}int HttpClient::noblock_connect(int sockfd, struct sockaddr *addrs, int addrlen)
{struct timeval timeout = {5, 0};int err = -1;fd_set fdset;int flag = 1;if (ioctl(sockfd, FIONBIO, &flag) != 0){printf("ioctl error\n");}int ret = connect(sockfd, addrs, addrlen);if (-1 == ret){if (EINPROGRESS == errno){FD_ZERO(&fdset);FD_SET(sockfd, &fdset);if (select(sockfd + 1, nullptr, &fdset, nullptr, &timeout) > 0){getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &err, (socklen_t *)&addrlen);if (0 == err){ret = 0;}else{ret = -1;}}else{ret = -1;}}}flag = 0;if (ioctl(sockfd, FIONBIO, &flag) != 0){printf("ioctl error\n");}if (ret < 0){print_netstat(err);}return ret;
}void HttpClient::print_netstat(int err)
{switch (err){case ENETUNREACH: // 网不通case EHOSTUNREACH:printf("network is unreachable err[%d]\n", err);break;case ECONNREFUSED: // 连接端口被拒绝printf("no-one listening on the remote address\n");break;case ETIMEDOUT: // 网络连接失败,服务器未响应printf("timeout while attempting connection the server may be to busy\n");break;default:printf("other errno %d\n", err);break;}
}int HttpClient::get_socket()
{int bufsize = 0x20000; // 128kint errnoret = -1;struct sockaddr_in serveraddr;int sockfd = socket(AF_INET, SOCK_STREAM, 0);if (sockfd < 0){return -1;}memset(&serveraddr, 0, sizeof(serveraddr));serveraddr.sin_family = AF_INET;split_url(url_, host_, port_);if (domain_judge(host_.c_str())){serveraddr.sin_addr.s_addr = host_get_by_name(host_.c_str());}else{serveraddr.sin_addr.s_addr = inet_addr(host_.c_str());}serveraddr.sin_port = htons(port_);if (set_buf_size(sockfd, bufsize, bufsize) < 0){close(sockfd);return -1;}if (set_sock_timeout(sockfd, 5, 0) < 0){close(sockfd);return -1;}int ret = noblock_connect(sockfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr));if (-1 == ret){close(sockfd);return -1;}return sockfd;
}int HttpClient::parse_test(std::string &msg)
{std::cout << msg << std::endl;return 0;
}int HttpClient::write_http(const std::string &method, const std::string &msg)
{std::string httpmsg = msg;int fd = get_socket();if (fd < 0){printf("fd is error\n");return -1;}make_http_msg(method, httpmsg);writen(fd, httpmsg.c_str(), httpmsg.size());std::string recvmsg = readn(fd, 2048);std::cout << recvmsg << std::endl;if (recvmsg.size()){parseFunc_ = std::bind(&HttpClient::parse_test, this, std::placeholders::_1);parse_recvmsg(recvmsg);}return 0;
}void test()
{HttpClient client("192.168.95.1:8080");client.write_http("post", "hello\n");
}int main()
{test();return 0;
}

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

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

相关文章

等级保护建设全流程

等保&#xff0c;全称为信息安全等级保护&#xff0c;是对信息和信息载体按照重要性等级分级进行保护的一种工作。 企业的信息系统有收集、储存用户信息的&#xff0c;都需要进行等保建设&#xff0c;以此来整改提升系统的安全防护能力&#xff0c;降低被攻击的风险。若不然一旦…

全志R128内存泄漏调试案例

内存泄露调试案例 问题背景 硬件&#xff1a;R128 软件&#xff1a;FreeRTOS rtplayer_test(Cedarx) AudioSystem 问题复现 复现步骤&#xff1a; rtplayer_test /data/boot.mp3串口输入"l", 循环播放串口输入"b" , 播放器后台执行 具体表现 rtpla…

Re50:读论文 Large Language Models Struggle to Learn Long-Tail Knowledge

诸神缄默不语-个人CSDN博文目录 诸神缄默不语的论文阅读笔记和分类 论文名称&#xff1a;Large Language Models Struggle to Learn Long-Tail Knowledge ArXiv网址&#xff1a;https://arxiv.org/abs/2211.08411 官方GitHub项目&#xff08;代码和实体&#xff09;&#xf…

找不到msvcp110.dll怎么办,msvcp110.dll丢失的修复方法

您可能已经碰见过这样的情况&#xff0c;当您试图打开某个软件时&#xff0c;屏幕上突然跳出一个提示窗口&#xff0c;告诉您 “找不到msvcp110.dll”&#xff0c;“msvcp110.dll丢失”。遇到这种情况是不是让人很焦头烂额呀&#xff1f;别担心&#xff0c;接下来我就为您提供几…

【EI会议征稿】第三届能源利用与自动化国际学术会议(ICEUA 2024)

第三届能源利用与自动化国际学术会议&#xff08;ICEUA 2024&#xff09; 2024 3rd International Conference on Energy Utilization and Automation (ICEUA 2024) 2024年第三届能源利用与自动化国际学术会议&#xff08;ICEUA 2024&#xff09;将于2024年3月15-17日在中国武汉…

C++ 调用 Lua 函数

零、前言 Lua 作为一门脚本语言&#xff0c;可以作为 “配置文件”、“动态逻辑脚本” 等角色作用于宿主程序。 因为他是一门语言&#xff0c;所以他有以下的好处&#xff1a; 1. Lua 会处理语法细节&#xff0c;后续维护简单&#xff0c;并且可以有注释。 2. 可以编写逻辑&…

IDEA 快捷键汇总

目录 1、altinsert 2、ctrl/ 3、altenter 4、alt回车 5、ctrlD 6、ctrlaltL 7、ctrl点击 8、alt左键向下拉 9、ctrlaltv 10、ctrlaltwint 1、altinsert 快速创建代码&#xff0c;可以快速创建类中get set tostring等方法 2、ctrl/ 单行注释 3、altenter…

水库大坝安全监测系统守护水利工程安全的坚实后盾

WX-WY1 随着社会经济的发展和科技的进步&#xff0c;水利工程的安全问题越来越受到人们的关注。水库大坝作为水利工程的重要组成部分&#xff0c;其安全状况直接关系到周边地区人民的生命财产安全和生态环境。因此&#xff0c;建立一个高效、可靠的水库大坝安全监测系统至关重要…

update_engine-FilesystemVerifierAction和PostinstallRunnerAction

在介绍完了DownloadAction之后&#xff0c;还剩下FilesystemVerifierAction和PostinstallRunnerAction&#xff0c;下面开始对其进行分析。 FilesystemVerifierAction 在数据下载完成后&#xff0c;在DownloadAction中会切换到FilesystemVerifierAction void DownloadAction:…

特效!视频里的特效在哪制作——Adobe After Effects

今天&#xff0c;我们来谈谈一款在Adobe系列中推出的一款图形视频处理软件&#xff0c;适用于从事设计和视频特技的机构&#xff0c;包括电视台、动画制作公司、个人后期制作工作室以及多媒体工作室的属于层类型后期软件——Adobe After Effects。 Adobe After Effects&#xf…

PostgreSQL设置主键从1开始自增

和MySQL不同&#xff0c;在 PostgreSQL 中&#xff0c;设置主键从1开始自增并重新开始自增是通过序列&#xff08;sequence&#xff09;来实现的。以下是步骤&#xff1a; 步骤1&#xff1a;创建一个序列 CREATE SEQUENCE your_table_id_seqSTART 1INCREMENT 1MINVALUE 1MAXV…

qt槽函数的四种写法

槽函数的四种写法 一,Qt4写法 不推荐这种写法,如果SLGNAL写错了,或者信号名字,槽函数名字写错了.编译器检查不出来,导致程序无响应,引起不必要的误解 connect(ui.btnOpen,SLGNAL(clicked),this,SLOT(open()));二,Qt5写法 推荐使用这种写法&#xff0c;信号名字、槽函数名字…

Docker build报错总结,版本过新大避雷!

1.速度太慢报错&#xff0c;需要换源&#xff1b; 在DOCKERFILE中添加镜像&#xff1b; RUN echo "deb http://mirror.sjtu.edu.cn/debian bookworm main non-free contrib" > /etc/apt/sources.list&#xff0c; 2.即使在Dockerfile中换源&#xff0c;但在bul…

Java 中四种引用类型

Java 中有四种引用类型&#xff0c;分别是强引用、软引用、弱引用和虚引用。这四种引用类型在 Java 虚拟机中对对象的内存管理起着重要作用。以下是这四种引用类型的含义和区别&#xff1a; 强引用&#xff08;Strong Reference&#xff09;&#xff1a; 强引用是 Java 中最常…

gitlab利用CI多工程持续构建

搭建CI的过程中有多个工程的时候&#xff0c;一个完美的构建过程往往是子工程上的更新(push 或者是merge)触发父工程的构建&#xff0c;这就需要如下建立一个downstream pipeline 子仓库1 .gitlab-ci.yml stages:- buildbuild_job:stage: buildtrigger:project: test_user/tes…

Flutter笔记:目录与文件存储以及在Flutter中的使用(下)

Flutter笔记 目录与文件存储以及在Flutter中的使用&#xff08;下&#xff09; 文件读写与Flutter中文件管理 作者&#xff1a;李俊才 &#xff08;jcLee95&#xff09;&#xff1a;https://blog.csdn.net/qq_28550263 邮箱 &#xff1a;291148484163.com 本文地址&#xff1a;…

-bash: jps: command not found

背景 服务器的jdk通过yum 安装的&#xff0c;要用jps查询pid&#xff0c;提示找不到命令 yum install -y java-1.8.0-openjdk.x86_64 一、jps命令无法找到 [devhgh-tob-hsbc-dev-003 ~]$ jps -bash: jps: command not found 二、检查基础Java环境 [devhgh-tob-hsbc-dev-003 ~]…

计算机是如何工作的(简单介绍)

目录 一、冯诺依曼体系 二、CPU基本流程工作 逻辑⻔ 电⼦开关——机械继电器(Mechanical Relay) ⻔电路(Gate Circuit) 算术逻辑单元 ALU&#xff08;Arithmetic & Logic Unit&#xff09; 算术单元(ArithmeticUnit) 逻辑单元(Logic Unit) ALU 符号 寄存器(Regis…

KVM Cloud云平台

项目介绍 KVM Cloud 是一款基于Java实现的轻量级私有云平台&#xff0c;旨在帮助中小企业快速实现计算、存储、网络等资源的管理&#xff0c;让企业拥有自己的云平台&#xff0c;包括但不限于如下功能: 1、基于KVM的VM基础功能(创建、启动、停止、重装、webVNC等功能) 2、使用…

xftp连接wsl2

在WSL中默认是没有安装OpenSSH&#xff0c;需要自己安装。 安装 sudo apt update sudo apt install openssh-server检查是否安装成功 ssh -V配置ssh sudo vim /etc/ssh/ssh_config设置端口 Port 22启动ssh服务 sudo service ssh startxftp连接 主机地址&#xff1a;127.…