select_client_tvnull.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. /**
  2. * 验证select时间参数设置为NULL,select_client_tvnull.cpp
  3. * zhangyl 2018.12.25
  4. */
  5. #include <sys/types.h>
  6. #include <sys/socket.h>
  7. #include <arpa/inet.h>
  8. #include <unistd.h>
  9. #include <string.h>
  10. #include <errno.h>
  11. #include <iostream>
  12. #define SERVER_ADDRESS "127.0.0.1"
  13. #define SERVER_PORT 3000
  14. int main(int argc, char* argv[])
  15. {
  16. //创建一个socket
  17. int clientfd = socket(AF_INET, SOCK_STREAM, 0);
  18. if (clientfd == -1)
  19. {
  20. std::cout << "create client socket error." << std::endl;
  21. return -1;
  22. }
  23. //连接服务器
  24. struct sockaddr_in serveraddr;
  25. serveraddr.sin_family = AF_INET;
  26. serveraddr.sin_addr.s_addr = inet_addr(SERVER_ADDRESS);
  27. serveraddr.sin_port = htons(SERVER_PORT);
  28. if (connect(clientfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr)) == -1)
  29. {
  30. std::cout << "connect socket error." << std::endl;
  31. close(clientfd);
  32. return -1;
  33. }
  34. int ret;
  35. while (true)
  36. {
  37. fd_set readset;
  38. FD_ZERO(&readset);
  39. //将侦听socket加入到待检测的可读事件中去
  40. FD_SET(clientfd, &readset);
  41. //timeval tm;
  42. //tm.tv_sec = 0;
  43. //tm.tv_usec = 0;
  44. //暂且只检测可读事件,不检测可写和异常事件
  45. ret = select(clientfd + 1, &readset, NULL, NULL, NULL);
  46. if (ret == -1)
  47. {
  48. //除了被信号中断的情形,其他情况都是出错
  49. if (errno != EINTR)
  50. break;
  51. }
  52. else if (ret == 0)
  53. {
  54. //select函数超时
  55. std::cout << "no event in specific time interval." << std::endl;
  56. continue;
  57. }
  58. else
  59. {
  60. if (FD_ISSET(clientfd, &readset))
  61. {
  62. //检测到可读事件
  63. char recvbuf[32];
  64. memset(recvbuf, 0, sizeof(recvbuf));
  65. //假设对端发数据的时候不超过31个字符。
  66. int n = recv(clientfd, recvbuf, 32, 0);
  67. if (n < 0)
  68. {
  69. //除了被信号中断的情形,其他情况都是出错
  70. if (errno != EINTR)
  71. break;
  72. }
  73. else if (n == 0)
  74. {
  75. //对端关闭了连接
  76. break;
  77. }
  78. else
  79. {
  80. std::cout << "recv data: " << recvbuf << std::endl;
  81. }
  82. }
  83. else
  84. {
  85. std::cout << "other socket event." << std::endl;
  86. }
  87. }
  88. }
  89. //关闭socket
  90. close(clientfd);
  91. return 0;
  92. }