-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnode.cpp
116 lines (92 loc) · 2.31 KB
/
node.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
#include "node.h"
NodeInfo:: NodeInfo(const char * p, const char * ip){
strncpy(port,p,10);
strncpy(IP, ip,20);
}
NodeInfo:: NodeInfo(){
}
Node:: Node(const char* port, const char * ip){
strncpy(myInfo.port,port,10);
strncpy(myInfo.IP, ip,20);
timerProcess =NULL;
}
void Node:: run(){
pthread_t tid;
Arg * args= (Arg*)malloc(sizeof(Arg));
args->n = this;
args->myPort = atoi(myInfo.port);
Pthread_create(&tid, NULL, listenThread, (void*)args);
Pthread_detach(tid);
}
void * listenThread(void * a){
int listenfd, optval;
pthread_t tid;
Arg * myargs = (Arg *)a;
/* important to use SO_REUSEADDR or can't restart proxy quickly */
printf("%d\n",myargs->myPort);
listenfd = Open_listenfd(myargs->myPort);
optval = 1;
setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, (const void*)&optval, sizeof(int));
while(1) {
Arg * args = (Arg *) malloc(sizeof(*args));
args->connfd = Accept(listenfd, NULL, NULL);
args->n = myargs->n;
Pthread_create(&tid, NULL, receiveRequest, (void*)args);
Pthread_detach(tid);
}
free(myargs);
}
void * receiveRequest(void * a){
int clientfd;
int byteCount = 0;
rio_t client;
char * saveptr=NULL;
char * cmd;
Arg * args = (Arg *)a;
clientfd = args->connfd;
Rio_readinitb( &client,clientfd);
args->n->processRequest(client,clientfd);
free(args);
}
void Node:: sendNodeInfo(int fd){
char buf[MAXLINE];
sprintf(buf,"%s*%s\n",myInfo.IP,myInfo.port);
Rio_writep(fd, buf, strlen(buf));
}
NodeInfo Node:: readNodeInfo(rio_t & r){
NodeInfo ans ;
int numBytes;
char * saveptr;
char buf[MAXLINE];
char * temp;
numBytes = Rio_readlineb(&r, buf, MAXLINE);
printf("h::%s\n",buf);
temp = strtok_r(buf, "*\r\n",&saveptr);
strncpy(ans.IP,temp,20);
temp = strtok_r(NULL, "*\r\n",&saveptr);
strncpy(ans.port,temp,10);
return ans;
}
int Node:: connectTo(NodeInfo & n){
int fd=Open_clientfd(n.IP, atoi(n.port));
return fd;
}
void Node:: timerStart(){
pthread_t timerTid;
if(timerProcess !=NULL){
Pthread_create(&timerTid,NULL,heartBeat,(void*)timerProcess);
Pthread_detach(timerTid);
}
}
Node::~ Node(){
if(timerProcess!= NULL){
delete(timerProcess);
}
}
void * heartBeat(void * args){
TimerProcess *s = (TimerProcess *) args;
while(true){
sleep(3);
s->invoke();
}
}