我有以下代码,它在 windows env 下运行得很好,而在 linux 中使用相同的代码却没有(除了 libs 的少量更改)。select 函数不响应新连接。
相关代码如下:
struct SocketState
{
int id; // Socket handle
int recv; // Receiving?
int send; // Sending?
int sendSubType; // Sending sub-type
char buffer[128];
int len;
int authenticate;
char userName[10];
};
struct SocketState sockets[MAX_SOCKETS]={0};
int socketsCount = 0;
int main()
{
int listenSocket = socket(PF_INET, SOCK_STREAM, 0);
if (-1 == listenSocket)
{
return 0 ;
}
struct sockaddr_in serverService;
serverService.sin_family = AF_INET;
serverService.sin_addr.s_addr = htonl(INADDR_ANY);
serverService.sin_port = htons(TIME_PORT);
if (-1 == bind(listenSocket, (struct sockaddr*)&serverService, sizeof(serverService)))
{
perror("Couldn't bind socket");
return -1;
}
if (-1 == listen(listenSocket, 10))
{
perror("Couldn't listen to port");
}
addSocket(listenSocket, LISTEN);
while (true)
{
fd_set waitRecv;
FD_ZERO(&waitRecv);
for (int i = 0; i < MAX_SOCKETS; i++)
{
if ((sockets[i].recv == LISTEN) || (sockets[i].recv == RECEIVE))
FD_SET(sockets[i].id, &waitRecv);
}
fd_set waitSend;
FD_ZERO(&waitSend);
for (int i = 0; i < MAX_SOCKETS; i++)
{
if (sockets[i].send == SEND)
FD_SET(sockets[i].id, &waitSend);
}
int nfd;
nfd = select(0, &waitRecv, &waitSend, NULL, NULL);
if (nfd == -1)
{
return 0 ;
}
}
}