-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathSocketState.cpp
131 lines (114 loc) · 2.23 KB
/
SocketState.cpp
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
#include "SocketState.h"
#include "Socket.h"
EASY_NS_BEGIN
SocketState::SocketState(Socket *s, void *p)
: socket(s), param(p)
{
}
SocketState::~SocketState()
{
if (param) {
delete param;
param = 0;
}
}
SocketState* SocketState::create(Socket *s, StateType t, void *p)
{
SocketState *state = 0;
switch (t) {
case sConnecting:
state = new SocketStateConnecting(s, p);
break;
case sConnected:
state = new SocketStateConnected(s, p);
break;
case sListening:
state = new SocketStateListening(s, p);
break;
case sClose:
default:
state = new SocketState(s, p);
break;
}
if (state) {
state->type = t;
}
return state;
}
SocketStateConnecting::SocketStateConnecting(Socket *s, void *p)
: SocketState(s, p)
{
start = time(0);
}
void SocketStateConnecting::update()
{
float timeout = socket->getConnectTimeout();
if (timeout > 0 && (time(0) - start) >= timeout) {
// Note: after setState, this object is released!
Socket *s = socket;
s->setState(sDisconnected);
s->shutdown();
return;
}
if (socket->canWrite()) {
if (socket->checkConnected()) {
socket->onConnect();
} else {
Socket *s = socket;
s->setState(sDisconnected);
s->emitError();
}
}
}
SocketStateConnected::SocketStateConnected(Socket *s, void *p)
: SocketState(s, p)
{
last = time(0);
}
void SocketStateConnected::update()
{
int ret = socket->select();
if (ret & 1) {
// do read
Socket *s = socket;
s->recv();
// Note: s can be closed in recv(), may delete this state,
// and the code below which visit this will cause error.
if (s->isClosed()) {
return;
}
}
time_t now = time(0);
if (ret & 1) {
last = now;
} else {
// time out
float timeout = socket->getIOTimeout();
if (timeout > 0 && now - last >= timeout) {
socket->setIOTimeout(-1);
socket->emit(sTimeout);
}
}
}
SocketStateListening::SocketStateListening(Socket *s, void *p)
: SocketState(s, p)
{
}
void SocketStateListening::update()
{
if (!socket->isUdp()) {
if (socket->getConnections().size() < socket->getMaxConnections()) {
if (!socket->accept()) {
Socket *s = socket;
s->setState(sDisconnected);
s->emitError();
}
}
} else {
if (socket->canRead()) {
// do read
socket->recvfrom();
}
}
}
EASY_NS_END