-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevent_loop.cpp
More file actions
90 lines (81 loc) · 3.1 KB
/
Copy pathevent_loop.cpp
File metadata and controls
90 lines (81 loc) · 3.1 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 <vector>
#include <sys/socket.h>
#include <netinet/in.h>
#include <poll.h>
#include <unistd.h>
#include "struct.hpp"
#include "application.cpp"
using std::vector;
int main(){
int fd = socket(AF_INET, SOCK_STREAM,0);
int on = 1;
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,&on,sizeof(on));
struct sockaddr_in addr = {};
addr.sin_family = AF_INET;
addr.sin_port = htons(1234);
addr.sin_addr.s_addr = htonl(0);
int n = bind(fd,(const struct sockaddr*)&addr, sizeof(addr));
if(n){
perror("Couldn't bind.");
exit(1);
}
n = listen(fd,20);
if(n){
perror("Couldnt' listen.");
exit(1);
}
printf("Server is listening.\n");
vector<Conn*> fds;
vector<struct pollfd> poll_list;
while(true){
poll_list.clear();
struct pollfd str {fd,POLLIN,0};
poll_list.push_back(str);
for(int i =0;i<fds.size();i++){
if(fds[i]){
struct pollfd str = {fds[i]->fd,POLLERR,0};
if(fds[i]->want_read){
str.events|=POLLIN;
}
if(fds[i]->want_write){
str.events|=POLLOUT;
}
poll_list.push_back(str);
}
}
int n = poll(poll_list.data(),poll_list.size(),-1);
if(n<0 && errno == EINTR){
continue;
}
if(n<0){
perror("Poll returned an error.");
exit(1);
}
if(poll_list[0].revents){
if(Conn* con = handle_accept(fd)){
if(fds.size() <= con->fd){
fds.resize(con->fd+1);
}
fds[con->fd] = con;
}
}
for(int i = 1; i<poll_list.size();i++){
int result = poll_list[i].revents;
if(result & POLLIN){
handle_read(fds[poll_list[i].fd]);
}
if(result & POLLOUT){
handle_write(fds[poll_list[i].fd]);
}
int s = poll_list[i].fd;
if((fds[s]->want_close && !fds[s]->want_write) || (result & POLLERR)){
close(s);
printf("Connection closed with: %s:%d\n",fds[s]->addr,fds[s]->port);
delete fds[s]->addr;
delete fds[s];
fds[s] = NULL;
fflush(stdout);
}
}
}
}