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

Function udpserv

examples/network/udpserver.c:42–141  ·  view source on GitHub ↗

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

Source from the content-addressed store, hash-verified

40* @brief This function is for creating a udp server on RT-Thread
41*/
42static void udpserv(void *paramemter)
43{
44 int sock;
45 int bytes_read;
46 char *recv_data;
47 socklen_t addr_len;
48 struct sockaddr_in server_addr, client_addr;
49
50 struct timeval timeout;
51 fd_set readset;
52 /* Allocate space for recv_data */
53 /* 分配接收用的数据缓冲 */
54 recv_data = rt_malloc(BUFSZ);
55 if (recv_data == RT_NULL)
56 {
57 LOG_E("No memory");
58 return;
59 }
60 /* Create a socket and set it to SOCK_DGRAM(UDP) */
61 /* 创建一个socket,类型是SOCK_DGRAM,UDP类型 */
62 if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
63 {
64 LOG_E("Create socket error");
65 goto __exit;
66 }
67 /* Initialize server side address */
68 /* 初始化服务端地址 */
69 server_addr.sin_family = AF_INET;
70 server_addr.sin_port = htons(port);
71 server_addr.sin_addr.s_addr = INADDR_ANY;
72 rt_memset(&(server_addr.sin_zero), 0, sizeof(server_addr.sin_zero));
73 /* Bind socket to server side address */
74 /* 绑定socket到服务端地址 */
75 if (bind(sock, (struct sockaddr *)&server_addr,
76 sizeof(struct sockaddr)) == -1)
77 {
78 LOG_E("Unable to bind");
79 goto __exit;
80 }
81
82 addr_len = sizeof(struct sockaddr);
83 LOG_I("UDPServer Waiting for client on port %d...", port);
84
85 started = 1;
86 is_running = 1;
87
88 timeout.tv_sec = 3;
89 timeout.tv_usec = 0;
90
91 while (is_running)
92 {
93 FD_ZERO(&readset);
94 FD_SET(sock, &readset);
95
96 /* Wait for read or write */
97 if (select(sock + 1, &readset, RT_NULL, RT_NULL, &timeout) == 0)
98 continue;
99 /* The maximum size received from sock is BUFSZ-1 bytes*/

Callers

nothing calls this directly

Calls 8

rt_mallocFunction · 0.85
socketFunction · 0.85
rt_memsetFunction · 0.85
bindFunction · 0.85
recvfromFunction · 0.85
rt_freeFunction · 0.85
closesocketFunction · 0.85
selectFunction · 0.50

Tested by

no test coverage detected