我很困惑我通过 select() 有一个服务器。我可以接受一些客户。 但我只是在最后连接服务器时才从客户端读取信息。 例如:A、B、C 的客户端依次连接服务器。服务器只打印 来自 C 的数据。
当我 gdb 它时,它一直阻塞在 select() 中。 你能告诉我为什么吗?谢谢。 主要代码是:
谢谢,我已经更新了问题,并且我已经通过 http://www.gnu.org/s/hello/manual/libc/Server-Example.html 更改了代码
但是问题还是来了。 我仍然只从最后一个得到数据。我无法获取数据 来自前一个。
主要代码是:
int read_from_client( int filedes )
{
字符缓冲区[MAXMSG];
int nbytes;
nbytes = read( filedes, buffer, MAXMSG );
if ( nbytes < 0 )
{
/* Read error */
perror( "read" );
exit( EXIT_FAILURE );
}
else if ( nbytes == 0 )
/* End-of-file. */
return -1;
else
{
/* Data read. */
fprintf( stderr, "Server: got message: '%s'\n", buffer );
return 0;
}
int ts_server_poll( struct tcp_server *server, struct timeval *timeout )
{
无符号整型我;
int nready, sockfd, k, j;
<br>//reset the fd set
_server_set_fd( server );
printf( "maxfd is %d\n", maxfd );
FD_SET( server->fd, server->fd_set );
while ( 1 )
{
/* Block until input arrives on one or more active sockets. */
server->fd_readset = server->fd_set;
if ( select( FD_SETSIZE, server->fd_readset, NULL, NULL, NULL ) < 0 )
{
perror ( "select" );
exit( EXIT_FAILURE );
}
/* Service all the sockets with input pending */
for ( i = 0; i < FD_SETSIZE; ++i )
if ( FD_ISSET( i, server->fd_readset ) )
{
if ( i == server->fd )
{
/* Connection request on original socket. */
int new;
new = (int)accept( server->fd, 0, 0 );
if ( new < 0 )
{
perror( "accept" );
exit( EXIT_FAILURE );
}
FD_SET( new, server->fd_set );
}
else
{
/* Data arriving on an already-connected socket. */
if ( read_from_client( i ) < 0 )
{
close( i );
FD_CLR( i, server->fd_set );
}
最佳答案
您的代码遗漏了几件事……接受新连接,并遍历读取集中的所有描述符。
这是一个如何在服务器中使用 select 的完整示例:
关于c - 选择和一些客户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5865818/