-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsocket.hpp
90 lines (88 loc) · 2.34 KB
/
socket.hpp
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
#include "esp32-event.hpp"
#include <string.h>
#include <list>
class TcpSocket
{
public:
// typedef void(*FreeFunc)(void*);
struct Buffer
{
uint8_t* buf;
size_t size;
bool empty() const { return size < 1; }
Buffer(): buf(nullptr), size(0) {};
Buffer(const void* aBuf, size_t aSize)
: buf(new uint8_t[aSize]), size(aSize)
{
memcpy(buf, aBuf, aSize);
}
Buffer(Buffer&& other)
: buf(other.buf), size(other.size)
{
other.release();
}
~Buffer() { if (buf) delete[] buf; }
void moveFrom(Buffer& other)
{
free();
buf = other.buf;
size = other.size;
other.release();
}
void free()
{
if (!buf)
return;
delete[] buf;
size = 0;
}
void release()
{
buf = nullptr;
size = 0;
}
void allocAndCopy(const void* aBuf, size_t aSize)
{
assert(empty());
buf = new uint8_t[aSize];
size = aSize;
memcpy(buf, aBuf, aSize);
}
};
protected:
uv_poll_t mPoll;
Buffer mPartialSendBuf;
std::list<Buffer> mSendBufs;
void* mUserp;
bool mRecvCalled = false;
void onSocketWritable();
static void pollEventCb(uv_poll_t* handle, int status, int events);
void monitorWritable();
void dontMonitorWritable();
void monitorReadable();
void dontMonitorReadable();
public:
int fd() const { return mPoll.fd; }
const uv_poll_t& pollDesc() const { return mPoll; }
bool isWritable() const { return (mPartialSendBuf.empty()); }
TcpSocket(uv_loop_t* loop);
int send(const void* data, size_t len);
int recv(void* buf, size_t bufsize);
//====
virtual void onReadable() {}
virtual void onWritable() {}
virtual void onError(int code) {}
virtual void onDisconnect() {}
};
class TcpClientSocket: public TcpSocket
{
protected:
static void connectCb(uv_poll_t* handle, int status, int events);
public:
using TcpSocket::TcpSocket;
int connectStrIp(const char* ip, uint16_t port);
int connectHost(const char* host, uint16_t port);
int connectIp4(sockaddr_in& addr);
//====
virtual void onConnect() { printf("default onconnect()\n");}
};