MCPcopy Create free account
hub / github.com/RT-Thread/rt-thread / tcpclient

Function tcpclient

examples/network/tcpclient.c:45–185  ·  view source on GitHub ↗

* @brief This function is for creating a tcp client on RT-Thread */

Source from the content-addressed store, hash-verified

43* @brief This function is for creating a tcp client on RT-Thread
44*/
45static void tcpclient(void *arg)
46{
47 int ret;
48 char *recv_data;
49 int bytes_received;
50 int sock = -1;
51 struct hostent *host = RT_NULL;
52 struct sockaddr_in server_addr;
53
54 struct timeval timeout;
55 fd_set readset;
56 /* Get host address by parameter url(Domain name resolution if input domain) */
57 /* 通过函数入口参数url获得host地址(如果是域名,会做域名解析) */
58 host = gethostbyname(url);
59 if (host == RT_NULL)
60 {
61 LOG_E("Get host by name failed!");
62 return;
63 }
64 /* Allocate space for recv_data */
65 /* 分配用于存放接收数据的缓冲 */
66 recv_data = rt_malloc(BUFSZ);
67 if (recv_data == RT_NULL)
68 {
69 LOG_E("No memory");
70 return;
71 }
72 /* Create a socket and set it to SOCK_STREAM(TCP) */
73 /* 创建一个socket,类型是SOCKET_STREAM,TCP类型 */
74 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1)
75 {
76 /* Failed on creating socket */
77 /* 创建socket失败 */
78 LOG_E("Create socket error");
79 goto __exit;
80 }
81 /* Initialize server side address */
82 /* 初始化预连接的服务端地址 */
83 server_addr.sin_family = AF_INET;
84 server_addr.sin_port = htons(port);
85 server_addr.sin_addr = *((struct in_addr *)host->h_addr);
86 rt_memset(&(server_addr.sin_zero), 0, sizeof(server_addr.sin_zero));
87 /* Connect to server */
88 /* 连接到服务端 */
89 if (connect(sock, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1)
90 {
91 /* Failed on connecting to server */
92 /* 连接失败 */
93 LOG_E("Connect fail!");
94 goto __exit;
95 }
96
97 started = 1;
98 is_running = 1;
99
100 timeout.tv_sec = 3;
101 timeout.tv_usec = 0;
102

Callers

nothing calls this directly

Calls 12

gethostbynameFunction · 0.85
rt_mallocFunction · 0.85
socketFunction · 0.85
rt_memsetFunction · 0.85
connectFunction · 0.85
rt_strcmpFunction · 0.85
sendFunction · 0.85
rt_strlenFunction · 0.85
rt_freeFunction · 0.85
closesocketFunction · 0.85
selectFunction · 0.50
recvFunction · 0.50

Tested by

no test coverage detected