-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathBaseSocket.h
90 lines (72 loc) · 1.83 KB
/
BaseSocket.h
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
#ifndef __SOCKET_H__
#define __SOCKET_H__
#include <string>
#include "Ostype.h"
#include "Util.h"
using namespace std;
enum
{
SOCKET_STATE_IDLE,
SOCKET_STATE_LISTENING,
SOCKET_STATE_CONNECTING,
SOCKET_STATE_CONNECTED,
SOCKET_STATE_CLOSING
};
class CBaseSocket:public CRefObject
{
public:
CBaseSocket();
virtual ~CBaseSocket();
SOCKET GetSocket() {return m_socket;}
void SetSocket(SOCKET fd) {m_socket = fd;}
void SetState(uint8_t state) { m_state = state;}
void SetCallback(callback_t callback) { m_callback = callback;}
void SetCallbackData(void* data) { m_callback_data = data;}
void SetRemoteIP(char* ip) { m_remote_ip = ip;}
void SetRemotePort(uint16_t port) {m_remote_port = port;}
void SetSendBufSize(uint32_t send_size);
void SetRecvBufSize(uint32_t recv_size);
const char* GetRemoteIP() { return m_remote_ip.c_str();}
uint16_t GetRemotePort() { return m_remote_port;}
const char* GetLocalIP() { return m_local_ip.c_str();}
uint16_t GetLocalPort() { return m_local_port;}
public:
int Listen(
const char* server_ip,
uint16_t port,
callback_t callback,
void* callback_data
);
net_handle_t Connect(
const char* server_ip,
uint16_t port,
callback_t callback,
void* callback_data
);
int Send(void* buf, int len);
int Recv(void* buf, int len);
int Close();
public:
void OnRead();
void OnWrite();
void OnClose();
private:
int _GetErrorCode();
bool _IsBlock(int error_code);
void _SetNonblock(SOCKET fd);
void _SetReuseAddr(SOCKET fd);
void _SetNoDelay(SOCKET fd);
void _SetAddr(const char* ip , const uint16_t port, sockaddr_in *pAddr);
void _AcceptNewSocket();
private:
string m_remote_ip;
uint16_t m_remote_port;
string m_local_ip;
uint16_t m_local_port;
callback_t m_callback;
void* m_callback_data;
uint8_t m_state;
SOCKET m_socket;
};
CBaseSocket* FindBaseSocket(net_handle_t fd);
#endif