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

Function udpclient

examples/network/udpclient.c:36–95  ·  view source on GitHub ↗

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

Source from the content-addressed store, hash-verified

34* @brief This function is for creating a udp client on RT-Thread
35*/
36static void udpclient(void *arg)
37{
38 int sock;
39 struct hostent *host;
40 struct sockaddr_in server_addr;
41 /* Get host address by parameter URL (domain name resolution if input domain) */
42 /* 通过函数入口参数url获得host地址(如果是域名,会做域名解析) */
43 host = (struct hostent *) gethostbyname(url);
44 if (host == RT_NULL)
45 {
46 LOG_E("Get host by name failed!");
47 return;
48 }
49 /* Create a socket and set it to SOCK_DGRAM(UDP) */
50 /* 创建一个socket,类型是SOCK_DGRAM,UDP类型 */
51 if ((sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
52 {
53 /* Failed on creating socket */
54 LOG_E("Create socket error");
55 return;
56 }
57 /* Initialize server side address */
58 /* 初始化预连接的服务端地址 */
59 server_addr.sin_family = AF_INET;
60 server_addr.sin_port = htons(port);
61 server_addr.sin_addr = *((struct in_addr *)host->h_addr);
62 rt_memset(&(server_addr.sin_zero), 0, sizeof(server_addr.sin_zero));
63
64 started = 1;
65 is_running = 1;
66 /* The total sending number(count) */
67 /* 总计发送count次数据 */
68 while (count && is_running)
69 {
70 /* Send message to server side */
71 /* 发送数据到服务远端 */
72 sendto(sock, send_data, rt_strlen(send_data), 0,
73 (struct sockaddr *)&server_addr, sizeof(struct sockaddr));
74 /* Thread sleep for 1 second */
75 /* 线程休眠一段时间 */
76 rt_thread_mdelay(1000);
77 /* count decrease 1 */
78 /* 计数值减一 */
79 count --;
80 }
81
82 if (count == 0)
83 {
84 LOG_I("UDP client send data finished!");
85 }
86 /* Close the socket */
87 /* 关闭这个socket */
88 if (sock >= 0)
89 {
90 closesocket(sock);
91 sock = -1;
92 }
93 started = 0;

Callers

nothing calls this directly

Calls 7

gethostbynameFunction · 0.85
socketFunction · 0.85
rt_memsetFunction · 0.85
sendtoFunction · 0.85
rt_strlenFunction · 0.85
rt_thread_mdelayFunction · 0.85
closesocketFunction · 0.85

Tested by

no test coverage detected