1 /*
2  * Copyright (c) 2006-2023, 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 
11 #include <rtthread.h>
12 #include <string.h>
13 
14 #if !defined(SAL_USING_POSIX)
15 #error "Please enable SAL_USING_POSIX!"
16 #else
17 #include <sys/time.h>
18 #include <sys/select.h>
19 #endif
20 #include <sys/socket.h> /* socket.h header file is needed when using BSD socket */ /* 使用BSD socket,需要包含socket.h头文件 */
21 #include "netdb.h"
22 
23 #define DEBUG_TCP_CLIENT
24 
25 #define DBG_TAG               "TCP"
26 #ifdef DEBUG_TCP_CLIENT
27 #define DBG_LVL               DBG_LOG
28 #else
29 #define DBG_LVL               DBG_INFO /* DBG_ERROR */
30 #endif
31 #include <rtdbg.h>
32 
33 #include "lwip_demo.h"
34 
35 #ifdef SAM_LWIP_EXAMPLE
36 
37 #define BUFSZ   1024
38 
39 static int started = 0;
40 static int is_running = 0;
41 static char url[256] = "www.baidu.com";
42 static int port = 8080;
43 static const char send_data[] = "This is TCP Client from RT-Thread."; /* The message be sent */ /* 发送用到的数据 */
44 
45 /**
46 * @brief  This function is for creating a tcp client on RT-Thread
47 */
tcpclient(void * arg)48 static void tcpclient(void *arg)
49 {
50     int ret;
51     char *recv_data;
52     int bytes_received;
53     int sock = -1;
54     struct hostent *host = RT_NULL;
55     struct sockaddr_in server_addr;
56 
57     struct timeval timeout;
58     fd_set readset;
59     /* Get host address by parameter url(Domain name resolution if input domain) */
60     /* 通过函数入口参数url获得host地址(如果是域名,会做域名解析) */
61     host = gethostbyname(url);
62     if (host == RT_NULL)
63     {
64         LOG_E("Get host by name failed!");
65         return;
66     }
67     /* Allocate space for recv_data */
68     /* 分配用于存放接收数据的缓冲 */
69     recv_data = rt_malloc(BUFSZ);
70     if (recv_data == RT_NULL)
71     {
72         LOG_E("No memory");
73         return;
74     }
75     /* Create a socket and set it to SOCK_STREAM(TCP) */
76     /* 创建一个socket,类型是SOCKET_STREAM,TCP类型 */
77     if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1)
78     {
79         /* Failed on creating socket */
80         /* 创建socket失败 */
81         LOG_E("Create socket error");
82         goto __exit;
83     }
84     /* Initialize server side address */
85     /* 初始化预连接的服务端地址 */
86     server_addr.sin_family = AF_INET;
87     server_addr.sin_port = htons(port);
88     server_addr.sin_addr = *((struct in_addr *)host->h_addr);
89     rt_memset(&(server_addr.sin_zero), 0, sizeof(server_addr.sin_zero));
90     /* Connect to server */
91     /* 连接到服务端 */
92     if (connect(sock, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1)
93     {
94         /* Failed on connecting to server */
95         /* 连接失败 */
96         LOG_E("Connect fail!");
97         goto __exit;
98     }
99 
100     started = 1;
101     is_running = 1;
102 
103     timeout.tv_sec = 3;
104     timeout.tv_usec = 0;
105 
106     while (is_running)
107     {
108         FD_ZERO(&readset);
109         FD_SET(sock, &readset);
110 
111         /* Wait for read */
112         if (select(sock + 1, &readset, RT_NULL, RT_NULL, &timeout) == 0)
113             continue;
114         /* Receive the maximum size 1024 bytes from socket */
115         /* 从sock连接中接收最大BUFSZ - 1字节数据 */
116         bytes_received = recv(sock, recv_data, BUFSZ - 1, 0);
117         if (bytes_received < 0)
118         {
119             /* Receive failed and close the connection */
120             /* 接收失败,关闭这个连接 */
121             LOG_E("Received error, close the socket.");
122             goto __exit;
123         }
124         else if (bytes_received == 0)
125         {
126             /* Print warning message when recv function returns 0 */
127             /* 打印recv函数返回值为0的警告信息 */
128             LOG_W("Received warning, recv function returns 0.");
129             continue;
130         }
131         else
132         {
133             /* Receive data successfully and append '\0' at the end of message */
134             /* 有接收到数据,把末端清零 */
135             recv_data[bytes_received] = '\0';
136 
137             if (rt_strcmp(recv_data, "q") == 0 || rt_strcmp(recv_data, "Q") == 0)
138             {
139                 /* If the first letter is 'q' or 'Q', close the connection */
140                 /* 如果是首字母是q或Q,关闭这个连接 */
141                 LOG_I("Got a 'q' or 'Q', close the socket.");
142                 goto __exit;
143             }
144             else
145             {
146                 /* Show the message in terminal */
147                 /* 在控制终端显示收到的数据 */
148                 LOG_D("Received data = %s", recv_data);
149             }
150         }
151         /* Send message to connected socket */
152         /* 发送数据到sock连接 */
153         ret = send(sock, send_data, rt_strlen(send_data), 0);
154         if (ret < 0)
155         {
156             /* Send failed, close the connection */
157             /* 发送失败,关闭这个连接 */
158             LOG_I("send error, close the socket.");
159             goto __exit;
160         }
161         else if (ret == 0)
162         {
163             /* Print warning message when send function returns 0 */
164             /* 打印send函数返回值为0的警告信息 */
165             LOG_W("Send warning, send function returns 0.");
166         }
167     }
168 
169 __exit:
170     if (recv_data)
171     {
172         rt_free(recv_data);
173         recv_data = RT_NULL;
174     }
175     if (sock >= 0)
176     {
177         closesocket(sock);
178         sock = -1;
179     }
180     started = 0;
181     is_running = 0;
182     return;
183 }
184 
185 /**
186  * @brief    Call this function will run LWIP example code.
187  *
188  * @note     .
189  *
190  * @param    None.
191  *
192  * @return   RT_OK or -RT_ERROR.
193  */
194 
lwip_demo_run(void)195 rt_err_t lwip_demo_run(void)
196 {
197     rt_thread_t tid;
198 
199     tid = rt_thread_create("tcp_client",
200                            tcpclient, RT_NULL,
201                            2048, RT_THREAD_PRIORITY_MAX/3, 20);
202     if (tid != RT_NULL)
203     {
204         rt_thread_startup(tid);
205     }
206 
207     return RT_EOK;
208 }
209 #endif
210 
211 /*@}*/
212