我需要使代码更可读,但它有很多周期,我能解决这个问题吗?
变量不断地跳来跳去,调试时很不方便观察。
for(;;)
{
//
// For connection orientated protocols, we will handle the
// packets received from a connection collectively. For datagram
// protocols, we have to handle each datagram individually.
//
//
// Check to see if we have any sockets remaining to be served
// from previous time through this loop. If not, call select()
// to wait for a connection request or a datagram to arrive.
//
for (i = 0; i < numSocket; i++)
{
if (FD_ISSET(servSock[i], &SockSet))
break;
}
if (i == numSocket)
{
for (i = 0; i < numSocket; i++)
{
FD_SET(servSock[i], &SockSet);
}
if (select(numSocket, &SockSet, 0, 0, 0) == SOCKET_ERROR)
continue;
}
for (i = 0; i < numSocket; i++)
{
if (FD_ISSET(servSock[i], &SockSet))
{
FD_CLR(servSock[i], &SockSet);
break;
}
}
...
}
最佳答案
为了使代码更具可读性(以及可测试性和可维护性),可以使用有意义的名称将一些逻辑封装到单独的函数中。考虑这个版本的循环
for(;;)
{
int i = find_socket_to_be_served(numSocket, servSock, &SockSet);
if (i == numSocket)
{
set_all_sockets(numSocket, servSock, &SockSet);
if (select(numSocket, &SockSet, 0, 0, 0) == SOCKET_ERROR)
continue;
}
// ...
}
其中使用的两个函数定义为
int find_socket_to_be_served(int n_sockets, int *fds, fd_set *fdset)
{
int i = 0;
for (; i < n_sockets; i++)
{
if (FD_ISSET(fds[i], fdset))
{
FD_CLR(fds[i], fdset);
break;
}
}
return i;
}
void set_all_sockets(int n_sockets, int *fds, fd_set *fdset)
{
for (int i = 0; i < n_sockets; i++)
{
FD_SET(fds[i], fdset);
}
}