1
+
2
+ int fullpred = 1 , fullsucc = 1 , fullafd = 1 ;
3
+ buffer1 [128 ]= "\0" , buffer2 [128 ]= "\0" , buffer3 [128 ]= "\0" ;
4
+
5
+
6
+
7
+
8
+
9
+ if (state == busy && FD_ISSET (afd ,& rfds )){
10
+ //checks is the full message was received and puts it together if not
11
+ readTCP (afd , buffer1 , & fullafd );
12
+ if (fullafd == 1 ){
13
+ //if the server has the full message it can handle it
14
+ if (messageHandler (afd , buffer1 )){
15
+ state = idle ;
16
+ write (1 , "received: " ,10 );
17
+ write (1 , buffer1 , strlen (buffer1 ));
18
+ cleanBuffer (buffer1 );
19
+ }
20
+ }
21
+ else {
22
+ close (afd );
23
+ state = idle ;
24
+ }
25
+
26
+
27
+
28
+
29
+ //reads input from successor
30
+ else if (succ_fd > 0 && FD_ISSET (succ_fd ,& rfds )){
31
+ //checks is the full message was received and puts it together if not
32
+ readTCP (succ_fd , buffer2 , & fullsucc );
33
+ if (fullsucc == 1 ){
34
+ //if the server has the full message it can handle it
35
+ succMessageHandler (buffer2 );
36
+ write (1 , "received from succ: " ,20 );
37
+ write (1 , buffer2 , strlen (buffer2 ));
38
+ cleanBuffer (buffer2 );
39
+ }
40
+ else if (fullsucc == -1 ){
41
+ succLeft ();
42
+ fullsucc = 1 ;
43
+ }
44
+ }
45
+
46
+
47
+ else if (pred_fd > 0 && FD_ISSET (pred_fd ,& rfds )){
48
+ //checks is the full message was received and puts it together if not
49
+ readTCP (pred_fd , buffer3 , & fullpred );
50
+ if (fullpred == 1 ){
51
+ //if the server has the full message it can handle it
52
+ predMessageHandler (buffer3 );
53
+ write (1 , "received from pred: " ,20 );
54
+ write (1 , buffer3 , strlen (buffer3 ));
55
+ cleanBuffer (buffer3 );
56
+ }
57
+ }
58
+
59
+
60
+ //sets the provided buffer to '\0'
61
+ void cleanBuffer (char * buff ){
62
+ for (int i = 0 ; i < strlen (buff ); i ++ ){
63
+ buff [i ]= '\0' ;
64
+ }
65
+ }
66
+
67
+ //reads the available content from a given fd
68
+ void readTCP (int fd , char * buff , int * full ){
69
+
70
+ ssize_t n ;
71
+ char temp [128 ];
72
+ int i = 0 ;
73
+ if ((n = read (fd ,temp ,128 ))!= 0 ){
74
+ if (n == -1 ) exit (1 );
75
+
76
+ //if the last message was fully received or if its the first message, copies temp to buff
77
+ if (* full == 1 ){
78
+ strcpy (buff ,temp );
79
+ }
80
+ else {
81
+ //if *full is different from 1 it means that the message wasnt received all together and we have to concatenate the strings
82
+ strcat (buff , temp );
83
+ }
84
+ //checks if the message was fully received (search for '\n')
85
+ for (i = 0 ; i < strlen (temp ); i ++ ){
86
+ if (strchr (temp , '\n' )!= NULL ){
87
+ * full = 1 ;
88
+ return ;
89
+ }
90
+ }
91
+ * full = 0 ;
92
+ }else * full = -1 ; //a server has left
93
+ }
0 commit comments