135 lines
2.8 KiB
C++
135 lines
2.8 KiB
C++
//
|
|
// Created by dongl on 23-5-10.
|
|
//
|
|
|
|
#include <cstring>
|
|
#include <thread>
|
|
#include "Client.h"
|
|
#include "../../../MP/Mph.h"
|
|
#include "../../../MP/Response.h"
|
|
|
|
|
|
Client::Client(const std::string&& ip, int port) : ip(ip), port(port) {
|
|
|
|
}
|
|
|
|
void Client::init(const std::string &ip, int port) {
|
|
// 初始化时间集合
|
|
base = event_base_new();
|
|
// init socket 初始化socket
|
|
bev = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE);
|
|
|
|
// 添加事件
|
|
bufferevent_setcb(bev, readcb, writecb, eventcb, base);
|
|
// 启用事件
|
|
bufferevent_enable(bev, EV_READ | EV_WRITE);
|
|
|
|
// 服务器地址
|
|
auto c_sin = addr(ip, port);
|
|
// 连接
|
|
int ret = bufferevent_socket_connect(bev, (sockaddr *)&c_sin, sizeof(c_sin));
|
|
// 是否链接成功
|
|
if (ret == 0) {
|
|
printf("server connected success!\n");
|
|
fflush(stdout);
|
|
}
|
|
}
|
|
|
|
sockaddr_in Client::addr(const std::string &ip, int port) {
|
|
sockaddr_in c_sin = {0};
|
|
memset(&c_sin, 0, sizeof(c_sin));
|
|
c_sin = {
|
|
AF_INET,
|
|
htons(port),
|
|
|
|
};
|
|
evutil_inet_pton(AF_INET, ip.c_str(), &c_sin.sin_addr.s_addr);
|
|
return c_sin;
|
|
}
|
|
|
|
void Client::run() {
|
|
std::thread thread([&]() {
|
|
init(ip, port);
|
|
printf("111");
|
|
event_base_loop(base, EVLOOP_NO_EXIT_ON_EMPTY);
|
|
printf("111");
|
|
});
|
|
thread.detach();
|
|
}
|
|
|
|
Client::~Client() {
|
|
bufferevent_free(bev);
|
|
event_base_free(base);
|
|
}
|
|
|
|
void Client::send_data(const std::string &data) {
|
|
bufferevent_write(bev, data.c_str(), data.size());
|
|
}
|
|
|
|
/// ************ 三个回调 **************////
|
|
void Client::readcb(struct bufferevent *bev, void *ctx) {
|
|
printf("[read]: ");
|
|
// read L 读包长度
|
|
uint8_t packetLen;
|
|
bufferevent_read(bev, &packetLen, 1);
|
|
// read V 读包头
|
|
char data_h[256] = {0};
|
|
bufferevent_read(bev, data_h, packetLen);
|
|
|
|
auto mph = std::make_shared<mp::mph>(mp::mph());
|
|
mph->ParseFromString(data_h);
|
|
printf("mph->mpb_size: %d\n", mph->mpb_size());
|
|
|
|
|
|
// read V 读包体 包头内含有包体长度
|
|
char data_b[256] = {0};
|
|
bufferevent_read(bev, data_b, mph->mpb_size());
|
|
printf("data_b: %s\n", data_b);
|
|
|
|
mp::response* resp = new mp::response();
|
|
resp->ParseFromString(data_b);
|
|
printf("%s\n", resp->sri().sri_msg().c_str());
|
|
|
|
fflush(stdout);
|
|
}
|
|
|
|
void Client::writecb(struct bufferevent *bev, void *ctx) {
|
|
printf("[write]: %p\n", ctx);
|
|
fflush(stdout);
|
|
}
|
|
|
|
void Client::eventcb(struct bufferevent *bev, short what, void *ctx) {
|
|
printf("[event]: %p\n", ctx);
|
|
|
|
if (what == BEV_EVENT_ERROR) {
|
|
printf("[BEV_EVENT_ERROR]: %p\n", ctx);
|
|
}
|
|
else if (what == BEV_EVENT_EOF) {
|
|
printf("[BEV_EVENT_ERROR]\n");
|
|
}
|
|
else if (what == BEV_EVENT_CONNECTED) {
|
|
printf("[BEV_EVENT_ERROR]\n");
|
|
}
|
|
fflush(stdout);
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|