web.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /* include web1 */
  2. #include "web.h"
  3. int
  4. main(int argc, char **argv)
  5. {
  6. int i, fd, n, maxnconn, flags, error;
  7. char buf[MAXLINE];
  8. fd_set rs, ws;
  9. if (argc < 5)
  10. err_quit("usage: web <#conns> <hostname> <homepage> <file1> ...");
  11. maxnconn = atoi(argv[1]);
  12. nfiles = min(argc - 4, MAXFILES);
  13. for (i = 0; i < nfiles; i++) {
  14. file[i].f_name = argv[i + 4];
  15. file[i].f_host = argv[2];
  16. file[i].f_flags = 0;
  17. }
  18. printf("nfiles = %d\n", nfiles);
  19. home_page(argv[2], argv[3]);
  20. FD_ZERO(&rset);
  21. FD_ZERO(&wset);
  22. maxfd = -1;
  23. nlefttoread = nlefttoconn = nfiles;
  24. nconn = 0;
  25. /* end web1 */
  26. /* include web2 */
  27. while (nlefttoread > 0) {
  28. while (nconn < maxnconn && nlefttoconn > 0) {
  29. /* 4find a file to read */
  30. for (i = 0 ; i < nfiles; i++)
  31. if (file[i].f_flags == 0)
  32. break;
  33. if (i == nfiles)
  34. err_quit("nlefttoconn = %d but nothing found", nlefttoconn);
  35. start_connect(&file[i]);
  36. nconn++;
  37. nlefttoconn--;
  38. }
  39. rs = rset;
  40. ws = wset;
  41. n = Select(maxfd+1, &rs, &ws, NULL, NULL);
  42. for (i = 0; i < nfiles; i++) {
  43. flags = file[i].f_flags;
  44. if (flags == 0 || flags & F_DONE)
  45. continue;
  46. fd = file[i].f_fd;
  47. if (flags & F_CONNECTING &&
  48. (FD_ISSET(fd, &rs) || FD_ISSET(fd, &ws))) {
  49. n = sizeof(error);
  50. if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &error, &n) < 0 ||
  51. error != 0) {
  52. err_ret("nonblocking connect failed for %s",
  53. file[i].f_name);
  54. }
  55. /* 4connection established */
  56. printf("connection established for %s\n", file[i].f_name);
  57. FD_CLR(fd, &wset); /* no more writeability test */
  58. write_get_cmd(&file[i]);/* write() the GET command */
  59. } else if (flags & F_READING && FD_ISSET(fd, &rs)) {
  60. if ( (n = Read(fd, buf, sizeof(buf))) == 0) {
  61. printf("end-of-file on %s\n", file[i].f_name);
  62. Close(fd);
  63. file[i].f_flags = F_DONE; /* clears F_READING */
  64. FD_CLR(fd, &rset);
  65. nconn--;
  66. nlefttoread--;
  67. } else {
  68. printf("read %d bytes from %s\n", n, file[i].f_name);
  69. }
  70. }
  71. }
  72. }
  73. exit(0);
  74. }
  75. /* end web2 */