gpt4 book ai didi

c - C 中的 Select() 问题

转载 作者:行者123 更新时间:2023-11-30 17:46:16 25 4
gpt4 key购买 nike

所以这是我的问题,我有一个服务器在客户端连接时调用此代码,问题是,一旦客户端调用,它就会陷入无限循环,我不明白为什么。我希望代码在 Select 上再次等待另一个客户端连接,但相反,初始触发器继续导致永无止境的循环。

当一个客户端连接时输出:

Lets startYOOHELLO WORLD WE MATCH
Lets startYOOHELLO WORLD WE MATCH
...
.
.
.
..

最佳答案

你陷入无限循环的原因是因为you are not accepting new connections from the clients在你的无限循环和结构数组中的文件/套接字描述符 are not valid any more因为那些客户端已经终止。您选择了一个非常糟糕的 select 机制。

你应该这样做:

while(1)
{
FD_ZERO(&readfds);

//add master socket to set
FD_SET(master_socket, &readfds);
max_sd = master_socket;

//add child sockets to set
for ( i = 0 ; i < max_clients ; i++)
{
//socket descriptor
sd = client_socket[i];

//if valid socket descriptor then add to read list
if(sd > 0)
FD_SET( sd , &readfds);

//highest file descriptor number, need it for the select function
if(sd > max_sd)
max_sd = sd;
}

//wait for an activity on one of the sockets , timeout is NULL , so wait indefinitely
activity = select( max_sd + 1 , &readfds , NULL , NULL , NULL);

if ((activity < 0) && (errno!=EINTR))
{
printf("select error");
}

//If something happened on the master socket , then its an incoming connection
if (FD_ISSET(master_socket, &readfds))
{
if ((new_socket = accept(master_socket, (struct sockaddr *)&address, (socklen_t*)&addrlen))<0)
{
perror("accept");
exit(EXIT_FAILURE);
}

//inform user of socket number - used in send and receive commands
printf("New connection , socket fd is %d , ip is : %s , port : %d \n" , new_socket , inet_ntoa(address.sin_addr) , ntohs(address.sin_port));

//send new connection greeting message
if( send(new_socket, message, strlen(message), 0) != strlen(message) )
{
perror("send");
}

puts("Welcome message sent successfully");

//add new socket to array of sockets
for (i = 0; i < max_clients; i++)
{
//if position is empty
if( client_socket[i] == 0 )
{
client_socket[i] = new_socket;
printf("Adding to list of sockets as %d\n" , i);

break;
}
}
}

//else its some IO operation on some other socket :)
for (i = 0; i < max_clients; i++)
{
sd = client_socket[i];

if (FD_ISSET( sd , &readfds))
{
//Check if it was for closing , and also read the incoming message
if ((valread = read( sd , buffer, 1024)) == 0)
{
//Somebody disconnected , get his details and print
getpeername(sd , (struct sockaddr*)&address , (socklen_t*)&addrlen);
printf("Host disconnected , ip %s , port %d \n" , inet_ntoa(address.sin_addr) , ntohs(address.sin_port));

//Close the socket and mark as 0 in list for reuse
close( sd );
client_socket[i] = 0;
}

//Echo back the message that came in
else
{
//set the string terminating NULL byte on the end of the data read
buffer[valread] = '\0';
send(sd , buffer , strlen(buffer) , 0 );
}
}
}
}

return 0;
}

关于c - C 中的 Select() 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19364741/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com