select_client_tv0.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. /**
  2. * 验证select时间参数设置为0,select_client_tv0.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, &tm);
  46. std::cout << "tm.tv_sec: " << tm.tv_sec << ", tm.tv_usec: " << tm.tv_usec << std::endl;
  47. if (ret == -1)
  48. {
  49. //除了被信号中断的情形,其他情况都是出错
  50. if (errno != EINTR)
  51. break;
  52. }
  53. else if (ret == 0)
  54. {
  55. //select函数超时
  56. std::cout << "no event in specific time interval." << std::endl;
  57. continue;
  58. }
  59. else
  60. {
  61. if (FD_ISSET(clientfd, &readset))
  62. {
  63. //检测到可读事件
  64. char recvbuf[32];
  65. memset(recvbuf, 0, sizeof(recvbuf));
  66. //假设对端发数据的时候不超过31个字符。
  67. int n = recv(clientfd, recvbuf, 32, 0);
  68. if (n < 0)
  69. {
  70. //除了被信号中断的情形,其他情况都是出错
  71. if (errno != EINTR)
  72. break;
  73. }
  74. else if (n == 0)
  75. {
  76. //对端关闭了连接
  77. break;
  78. }
  79. else
  80. {
  81. std::cout << "recv data: " << recvbuf << std::endl;
  82. }
  83. }
  84. else
  85. {
  86. std::cout << "other socket event." << std::endl;
  87. }
  88. }
  89. }
  90. //关闭socket
  91. close(clientfd);
  92. return 0;
  93. }