-
Notifications
You must be signed in to change notification settings - Fork 202
/
HttpClient.cpp
112 lines (98 loc) · 2.45 KB
/
HttpClient.cpp
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
/*
Copyright © 2017-2020, orcaer@yeah.net All rights reserved.
Author: orcaer@yeah.net
Last modified: 2020-3-30
Description: https://github.com/wlgq2/uv-cpp
*/
#include "../include/http/HttpClient.h"
using namespace uv;
using namespace uv::http;
HttpClient::HttpClient(EventLoop* loop)
:client_(new TcpClient(loop)),
callback_(nullptr),
isConnected(false)
{
buffer_.resize(20480);
}
HttpClient::~HttpClient()
{
if (isConnected)
{
auto client = client_;
client->close([client](std::string& name)
{
delete client;
});
}
else
{
delete client_;
}
}
void HttpClient::Req(uv::SocketAddr& addr,Request& req)
{
req_ = req;
buffer_.clear();
client_->setConnectStatusCallback(std::bind(&HttpClient::onConnectStatus,this,std::placeholders::_1));
client_->setMessageCallback(std::bind(&HttpClient::onMessage, this, std::placeholders::_1, std::placeholders::_2));
client_->connect(addr);
}
void HttpClient::setOnResp(OnRespCallback callback)
{
callback_ = callback;
}
void HttpClient::onResp(int rst, Response* resp)
{
if (nullptr != callback_)
{
callback_(rst, resp);
}
}
void HttpClient::onConnectStatus(TcpClient::ConnectStatus status)
{
if (status == uv::TcpClient::ConnectStatus::OnConnectSuccess)
{
isConnected = true;
std::string str;
req_.pack(str);
client_->write(str.c_str(), (unsigned int)str.size());
}
else if (status == uv::TcpClient::ConnectStatus::OnConnnectFail)
{
isConnected = false;
onResp(ConnectFail, nullptr);
}
else
{
isConnected = false;
Response resp;
if (0 == resp.unpack(buffer_))
{
onResp(Success, &resp);
}
else
{
onResp(ParseFail, nullptr);
}
}
}
void HttpClient::onMessage(const char* data, ssize_t size)
{
unsigned bufsize = (unsigned)buffer_.size();
unsigned datasize = bufsize + (unsigned)size;
buffer_.resize(datasize);
char* out = (char*)buffer_.c_str() + bufsize;
std::copy(data, data + size, out);
Response resp;
auto rst = resp.unpackAndCompleted(buffer_);
if (rst == ParseResult::Success)
{
onResp(Success, &resp);
}
else if (rst == ParseResult::Error)
{
uv::LogWriter::Instance()->error("parse http's response error.");
//解析出错
buffer_.clear();
}
}