-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathechoserver.cc
More file actions
91 lines (73 loc) · 1.64 KB
/
echoserver.cc
File metadata and controls
91 lines (73 loc) · 1.64 KB
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 <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 ReadEvent : public BaseFileEvent {
public:
void OnEvents(uint32_t events) {
if (events & BaseFileEvent::READ) {
char a;
if (read(file, &a, sizeof(char)) == 0) {
close(file);
delete this;
return;
}
write(file, &a, sizeof(char));
}
if (events & BaseFileEvent::ERROR) {
close(file);
delete this;
}
}
};
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);
ReadEvent *e = new ReadEvent();
e->SetFile(fd);
e->SetEvents(BaseFileEvent::READ | BaseFileEvent::ERROR);
el.AddEvent(e);
}
if (events & BaseFileEvent::ERROR) {
close(file);
}
}
};
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", 22222);
if (fd == -1) {
printf("binding address %s", strerror(errno));
return -1;
}
e.SetFile(fd);
el.AddEvent(&e);
Signal s;
s.SetEvents(BaseSignalEvent::INT);
el.AddEvent(&s);
el.StartLoop();
return 0;
}