-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathexample.cc
152 lines (121 loc) · 2.46 KB
/
example.cc
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/time.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <errno.h>
#include "eventloop.h"
using namespace eventloop;
EventLoop el;
class BufferEvent : public BufferFileEvent {
public:
BufferEvent() {
state_ = 0;
Recive(buf_, 1);
}
void OnRecived(char *buffer, uint32_t len) {
switch (state_) {
case 0:
len_ = buf_[0] - '0';
Recive(buf_, len_);
state_ = 1;
break;
case 1:
Send(buf_, len_);
state_ = 2;
break;
default:
break;
}
}
void OnSent(char *buffer, uint32_t len) {
state_ = 0;
Recive(buf_, 1);
}
void OnError() {
}
private:
char buf_[1024];
int len_;
int state_;
};
class AcceptEvent: public BaseFileEvent {
public:
void OnEvents(uint32_t events) {
if (events & BaseFileEvent::READ) {
uint32_t size = 0;
struct sockaddr_in addr;
int fd = accept(file, (struct sockaddr*)&addr, &size);
BufferEvent *e = new BufferEvent();
e->SetFile(fd);
el.AddEvent(e);
}
if (events & BaseFileEvent::ERROR) {
close(file);
}
}
};
class Periodic : public PeriodicTimerEvent {
public:
void OnTimer() {
printf("Periodic timer\n");
}
};
class Timer : public BaseTimerEvent {
public:
void OnEvents(uint32_t events) {
printf("timer:%u\n", static_cast<uint32_t>(time(0)));
timeval tv = el.Now();
tv.tv_sec += 1;
SetTime(tv);
el.UpdateEvent(this);
if (!p) return;
if (p->IsRunning()) p->Stop();
else p->Start();
}
public:
Periodic *p;
};
class Signal : public BaseSignalEvent {
public:
void OnEvents(uint32_t events) {
printf("shutdown\n");
el.StopLoop();
}
};
int main(int argc, char **argv) {
int fd;
AcceptEvent e;
e.SetEvents(BaseFileEvent::READ | BaseFileEvent::ERROR);
fd = BindTo("0.0.0.0", 11112);
if (fd == -1) {
printf("binding address %s", strerror(errno));
return -1;
}
e.SetFile(fd);
el.AddEvent(&e);
Periodic p;
Timer t;
t.p = &p;
timeval tv;
gettimeofday(&tv, NULL);
tv.tv_sec += 3;
t.SetTime(tv);
el.AddEvent(&t);
timeval tv2;
tv2.tv_sec = 0;
tv2.tv_usec = 500 * 1000;
p.SetInterval(tv2);
el.AddEvent(&p);
p.Start();
Signal s;
s.SetEvents(BaseSignalEvent::INT);
el.AddEvent(&s);
el.StartLoop();
return 0;
}