select函数 (3)

ret = select(maxsock + 1, &fdsr, NULL, NULL, &tv);

  if (ret < 0)

  {

  perror("select");

  break;

  } else if (ret == 0)

  {

  printf("timeout\n");

  continue;

  }

  // check every fd in the set

  for (i = 0; i < conn_amount; i++)

  {

  if (FD_ISSET(fd_A[i], &fdsr))

  {

  ret = recv(fd_A[i], buf, sizeof(buf), 0);

  if (ret <= 0)

  {        // client close

  printf("client[%d] close\n", i);

  close(fd_A[i]);

  FD_CLR(fd_A[i], &fdsr);

  fd_A[i] = 0;

  }

  else

  {        // receive data

  if (ret < BUF_SIZE)

  memset(&buf[ret], '\0', 1);

  printf("client[%d] send:%s\n", i, buf);

  }

  }

  }

  // check whether a new connection comes

  if (FD_ISSET(sock_fd, &fdsr))

  {

  new_fd = accept(sock_fd, (struct sockaddr *)&client_addr, &sin_size);

  if (new_fd <= 0)

  {

  perror("accept");

  continue;

  }

  // add to fd queue

  if (conn_amount < BACKLOG)

  {

  fd_A[conn_amount++] = new_fd;

  printf("new connection client[%d] %s:%d\n", conn_amount,

  inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));

  if (new_fd > maxsock)

  maxsock = new_fd;

  }

  else

  {

  printf("max connections arrive, exit\n");

  send(new_fd, "bye", 4, 0);

  close(new_fd);

  break;

  }

  }

  showclient();

  }

  // close other connections

  for (i = 0; i < BACKLOG; i++)

  {

  if (fd_A[i] != 0)

  {

  close(fd_A[i]);

  }

  }

  exit(0);

  }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值