tcpclient.c 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. /*
  2. * Copyright (c) 2006-2022, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. * 2022-01-24 ChungHsuan improve code comments
  9. */
  10. #include <rtthread.h>
  11. #include <string.h>
  12. #include <stdlib.h>
  13. #if !defined(SAL_USING_POSIX)
  14. #error "Please enable SAL_USING_POSIX!"
  15. #else
  16. #include <sys/time.h>
  17. #include <sys/select.h>
  18. #endif
  19. #include <sys/socket.h> /* socket.h header file is needed when using BSD socket */ /* 使用BSD socket,需要包含socket.h头文件 */
  20. #include "netdb.h"
  21. #define DEBUG_TCP_CLIENT
  22. #define DBG_TAG "TCP"
  23. #ifdef DEBUG_TCP_CLIENT
  24. #define DBG_LVL DBG_LOG
  25. #else
  26. #define DBG_LVL DBG_INFO /* DBG_ERROR */
  27. #endif
  28. #include <rtdbg.h>
  29. #define BUFSZ 1024
  30. static int started = 0;
  31. static int is_running = 0;
  32. static char url[256];
  33. static int port = 8080;
  34. static const char send_data[] = "This is TCP Client from RT-Thread."; /* The message be sent */ /* 发送用到的数据 */
  35. /**
  36. * @brief This function is for creating a tcp client on RT-Thread
  37. */
  38. static void tcpclient(void *arg)
  39. {
  40. int ret;
  41. char *recv_data;
  42. int bytes_received;
  43. int sock = -1;
  44. struct hostent *host = RT_NULL;
  45. struct sockaddr_in server_addr;
  46. struct timeval timeout;
  47. fd_set readset;
  48. /* Get host address by parameter url(Domain name resolution if input domain) */
  49. /* 通过函数入口参数url获得host地址(如果是域名,会做域名解析) */
  50. host = gethostbyname(url);
  51. if (host == RT_NULL)
  52. {
  53. LOG_E("Get host by name failed!");
  54. return;
  55. }
  56. /* Allocate space for recv_data */
  57. /* 分配用于存放接收数据的缓冲 */
  58. recv_data = rt_malloc(BUFSZ);
  59. if (recv_data == RT_NULL)
  60. {
  61. LOG_E("No memory");
  62. return;
  63. }
  64. /* Create a socket and set it to SOCK_STREAM(TCP) */
  65. /* 创建一个socket,类型是SOCKET_STREAM,TCP类型 */
  66. if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1)
  67. {
  68. /* Failed on creating socket */
  69. /* 创建socket失败 */
  70. LOG_E("Create socket error");
  71. goto __exit;
  72. }
  73. /* Initialize server side address */
  74. /* 初始化预连接的服务端地址 */
  75. server_addr.sin_family = AF_INET;
  76. server_addr.sin_port = htons(port);
  77. server_addr.sin_addr = *((struct in_addr *)host->h_addr);
  78. rt_memset(&(server_addr.sin_zero), 0, sizeof(server_addr.sin_zero));
  79. /* Connect to server */
  80. /* 连接到服务端 */
  81. if (connect(sock, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1)
  82. {
  83. /* Failed on connecting to server */
  84. /* 连接失败 */
  85. LOG_E("Connect fail!");
  86. goto __exit;
  87. }
  88. started = 1;
  89. is_running = 1;
  90. timeout.tv_sec = 3;
  91. timeout.tv_usec = 0;
  92. while (is_running)
  93. {
  94. FD_ZERO(&readset);
  95. FD_SET(sock, &readset);
  96. /* Wait for read */
  97. if (select(sock + 1, &readset, RT_NULL, RT_NULL, &timeout) == 0)
  98. continue;
  99. /* Receive the maximum size 1024 bytes from socket */
  100. /* 从sock连接中接收最大BUFSZ - 1字节数据 */
  101. bytes_received = recv(sock, recv_data, BUFSZ - 1, 0);
  102. if (bytes_received < 0)
  103. {
  104. /* Receive failed and close the connection */
  105. /* 接收失败,关闭这个连接 */
  106. LOG_E("Received error(%d), close the socket.", errno);
  107. goto __exit;
  108. }
  109. else if (bytes_received == 0)
  110. {
  111. /* Socket has performed an orderly shutdown. */
  112. /* 连接已断开 */
  113. LOG_E("Socket has performed an orderly shutdown.");
  114. goto __exit;
  115. }
  116. else
  117. {
  118. /* Receive data successfully and append '\0' at the end of message */
  119. /* 有接收到数据,把末端清零 */
  120. recv_data[bytes_received] = '\0';
  121. if (rt_strcmp(recv_data, "q") == 0 || rt_strcmp(recv_data, "Q") == 0)
  122. {
  123. /* If the first letter is 'q' or 'Q', close the connection */
  124. /* 如果是首字母是q或Q,关闭这个连接 */
  125. LOG_I("Got a 'q' or 'Q', close the socket.");
  126. goto __exit;
  127. }
  128. else
  129. {
  130. /* Show the message in terminal */
  131. /* 在控制终端显示收到的数据 */
  132. LOG_D("Received data = %s", recv_data);
  133. }
  134. }
  135. /* Send message to connected socket */
  136. /* 发送数据到sock连接 */
  137. ret = send(sock, send_data, rt_strlen(send_data), 0);
  138. if (ret < 0)
  139. {
  140. /* Send failed, close the connection */
  141. /* 发送失败,关闭这个连接 */
  142. LOG_I("send error(%d), close the socket.", errno);
  143. goto __exit;
  144. }
  145. else if (ret == 0)
  146. {
  147. /* Socket has performed an orderly shutdown. */
  148. /* 连接已断开 */
  149. LOG_E("Socket has performed an orderly shutdown.");
  150. goto __exit;
  151. }
  152. else if (ret != rt_strlen(send_data))
  153. {
  154. LOG_W("%d out of %d bytes sent.", ret, rt_strlen(send_data));
  155. }
  156. }
  157. __exit:
  158. if (recv_data)
  159. {
  160. rt_free(recv_data);
  161. recv_data = RT_NULL;
  162. }
  163. if (sock >= 0)
  164. {
  165. closesocket(sock);
  166. sock = -1;
  167. }
  168. started = 0;
  169. is_running = 0;
  170. return;
  171. }
  172. /**
  173. * @brief The usage description of tcp client on rt-Thread
  174. */
  175. static void usage(void)
  176. {
  177. rt_kprintf("Usage: tcpclient -h <host> -p <port>\n");
  178. rt_kprintf(" tcpclient --stop\n");
  179. rt_kprintf(" tcpclient --help\n");
  180. rt_kprintf("\n");
  181. rt_kprintf("Miscellaneous:\n");
  182. rt_kprintf(" -h Specify host address\n");
  183. rt_kprintf(" -p Specify the host port number\n");
  184. rt_kprintf(" --stop Stop tcpclient program\n");
  185. rt_kprintf(" --help Print help information\n");
  186. }
  187. /**
  188. * @brief This function is for testing tcp client on rt-Thread
  189. */
  190. static void tcpclient_test(int argc, char** argv)
  191. {
  192. rt_thread_t tid;
  193. if (argc == 1 || argc > 5)
  194. {
  195. LOG_I("Please check the command you entered!\n");
  196. goto __usage;
  197. }
  198. else
  199. {
  200. if (rt_strcmp(argv[1], "--help") == 0)
  201. {
  202. goto __usage;
  203. }
  204. else if (rt_strcmp(argv[1], "--stop") == 0)
  205. {
  206. is_running = 0;
  207. return;
  208. }
  209. else if (rt_strcmp(argv[1], "-h") == 0 && rt_strcmp(argv[3], "-p") == 0)
  210. {
  211. if (started)
  212. {
  213. LOG_I("The tcpclient has started!");
  214. LOG_I("Please stop tcpclient firstly, by: tcpclient --stop");
  215. return;
  216. }
  217. if (rt_strlen(argv[2]) > sizeof(url))
  218. {
  219. LOG_E("The input url is too long, max %d bytes!", sizeof(url));
  220. return;
  221. }
  222. rt_memset(url, 0x0, sizeof(url));
  223. rt_strncpy(url, argv[2], rt_strlen(argv[2]));
  224. port = atoi(argv[4]);
  225. }
  226. else
  227. {
  228. goto __usage;
  229. }
  230. }
  231. tid = rt_thread_create("tcp_client",
  232. tcpclient, RT_NULL,
  233. 2048, RT_THREAD_PRIORITY_MAX/3, 20);
  234. if (tid != RT_NULL)
  235. {
  236. rt_thread_startup(tid);
  237. }
  238. return;
  239. __usage:
  240. usage();
  241. }
  242. #ifdef RT_USING_FINSH
  243. MSH_CMD_EXPORT_ALIAS(tcpclient_test, tcpclient,
  244. Start a tcp client. Help: tcpclient --help);
  245. #endif