IM_Client/api/core/Client.cpp

110 lines
2.1 KiB
C++

//
// Created by dongl on 23-5-10.
//
#include <cstring>
#include <thread>
#include "Client.h"
#include "management.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);
event_base_loop(base, EVLOOP_NO_EXIT_ON_EMPTY);
});
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) {
management::read_packet(bev);
}
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);
}