@@ -58,7 +58,7 @@ int main( int argc, char* argv[] )
5858 assert ( ret != -1 );
5959
6060 client_data* users = new client_data[FD_LIMIT];
61- pollfd fds[USER_LIMIT+1 ];
61+ pollfd fds[USER_LIMIT+1 ]; // size is 6
6262 int user_counter = 0 ;
6363 for ( int i = 1 ; i <= USER_LIMIT; ++i )
6464 {
@@ -78,9 +78,10 @@ int main( int argc, char* argv[] )
7878 break ;
7979 }
8080
81+ // 遍历fds查看哪些fd的事件触发
8182 for ( int i = 0 ; i < user_counter+1 ; ++i )
8283 {
83- if ( ( fds[i].fd == listenfd ) && ( fds[i].revents & POLLIN ) )
84+ if ( ( fds[i].fd == listenfd ) && ( fds[i].revents & POLLIN ) ) // listenfd可读表示有连接到来
8485 {
8586 struct sockaddr_in client_address;
8687 socklen_t client_addrlength = sizeof ( client_address );
@@ -119,11 +120,15 @@ int main( int argc, char* argv[] )
119120 continue ;
120121 }
121122 else if ( fds[i].revents & POLLRDHUP )
122- {
123+ { // 最后一个user移动到当前user的位置
123124 users[fds[i].fd ] = users[fds[user_counter].fd ];
125+ // close当前的fd
124126 close ( fds[i].fd );
127+ // fds数组中最后一个fd移动到当前的fd
125128 fds[i] = fds[user_counter];
129+ // 当前索引减一,防止异常和溢出
126130 i--;
131+ // user_counter减一
127132 user_counter--;
128133 printf ( " a client left\n " );
129134 }
@@ -138,17 +143,21 @@ int main( int argc, char* argv[] )
138143 if ( errno != EAGAIN )
139144 {
140145 close ( connfd );
146+ // 最后一个user移动到当前user的位置
141147 users[fds[i].fd ] = users[fds[user_counter].fd ];
148+ // 最后一个fd移动到当前的fds
142149 fds[i] = fds[user_counter];
150+ // 当前索引减一,防止异常和溢出
143151 i--;
144- user_counter--;
152+ // 最后把user_counter减一
153+ user_counter--;
145154 }
146155 }
147156 else if ( ret == 0 )
148157 {
149158 printf ( " code should not come to here\n " );
150159 }
151- else
160+ else // 正常接收到了数据
152161 {
153162 for ( int j = 1 ; j <= user_counter; ++j )
154163 {
@@ -157,13 +166,15 @@ int main( int argc, char* argv[] )
157166 continue ;
158167 }
159168
169+ // server收到一个client的数据后,广播给连接到同server的其他的client
160170 fds[j].events |= ~POLLIN;
161171 fds[j].events |= POLLOUT;
172+ // 收到的数据赋值给write_buf
162173 users[fds[j].fd ].write_buf = users[connfd].buf ;
163174 }
164175 }
165176 }
166- else if ( fds[i].revents & POLLOUT )
177+ else if ( fds[i].revents & POLLOUT ) // 检测到写数据事件
167178 {
168179 int connfd = fds[i].fd ;
169180 if ( ! users[connfd].write_buf )
0 commit comments