nim_duilib/examples/proto_debuger/tcp_client.h

89 lines
2.0 KiB
C
Raw Normal View History

2021-10-09 00:14:49 +08:00
//
// Created by 29019 on 2020/4/18.
//
2021-10-11 00:00:10 +08:00
#pragma once
2021-10-09 00:14:49 +08:00
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0500
#endif
2021-10-11 00:00:10 +08:00
2021-10-09 00:14:49 +08:00
#ifdef linux
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#define EVENT__HAVE_PTHREADS
#endif
extern "C"{
#include "event2/bufferevent.h"
2021-10-11 00:00:10 +08:00
#include "event2/bufferevent_struct.h"
2021-10-09 00:14:49 +08:00
#include "event2/buffer.h"
#include "event2/listener.h"
#include "event2/util.h"
#include "event2/event.h"
#include "event2/thread.h"
2021-10-11 00:00:10 +08:00
/* For int types. */
#include <event2/util.h>
/* For struct event */
#include <event2/event_struct.h>
2021-10-09 00:14:49 +08:00
};
2021-10-11 00:00:10 +08:00
2021-10-09 00:14:49 +08:00
#include<string.h>
#include <iostream>
#include <mutex>
#include <thread>
using namespace std;
class TcpClientLibevent {
public:
typedef enum {
2021-10-11 00:00:10 +08:00
UNCONNECTED, // 未连接
CONNECTED, //已经连接
FAIL, // 连接失败
2021-10-09 00:14:49 +08:00
}Status;
2021-10-11 00:00:10 +08:00
class TcpClientObserver {
2021-10-09 00:14:49 +08:00
public:
2021-10-11 00:00:10 +08:00
virtual ~TcpClientObserver() { return; }
2021-10-09 00:14:49 +08:00
mutex mMux;
virtual void OnConnected() { return; };
virtual void OnDisConnected() { return; };
2021-10-11 00:00:10 +08:00
virtual void OnData(uint8_t* dat, uint64_t len) { return; };
virtual void OnClose() { return; };
2021-10-09 00:14:49 +08:00
};
2021-10-11 00:00:10 +08:00
TcpClientLibevent(std::string addrinfo, int port, TcpClientObserver* p);
~TcpClientLibevent() {
2021-10-09 00:14:49 +08:00
event_base_free(mBase);
};
2021-10-11 00:00:10 +08:00
friend void conn_eventcb(struct bufferevent*, short, void*);
2021-10-09 00:14:49 +08:00
int ConnectServer();
bool Connected();
int Dispatch();
2021-10-11 00:00:10 +08:00
int OnTCPPackage(uint8_t*, uint16_t);
2021-10-09 00:14:49 +08:00
int SetReconnect(bool);
int SetObserver(TcpClientObserver*);
int Close();
2021-10-11 00:00:10 +08:00
uint64_t SocketFd();
2021-10-09 00:14:49 +08:00
Status mStatus;
2021-10-11 00:00:10 +08:00
TcpClientObserver* mObserver;
2021-10-09 00:14:49 +08:00
private:
bool mReConnect = false;
2021-10-11 00:00:10 +08:00
int sendData(void*, size_t);
struct event_base* mBase;
2021-10-09 00:14:49 +08:00
struct bufferevent* bev;
struct sockaddr_in mSrv;
2021-10-11 00:00:10 +08:00
std::thread* mThread;
mutex mLock; // 互斥锁
uint64_t mByteSend; // 发送字节数
uint64_t mByteRecv; // 接收字节数
evutil_socket_t mSocketFD; // 操作系统原生socket
2021-10-09 00:14:49 +08:00
};
2021-10-11 00:00:10 +08:00