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

Function tcpserv

examples/network/tcpserver.c:44–223  ·  view source on GitHub ↗

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

Source from the content-addressed store, hash-verified

42* @brief This function is for creating a tcp server on RT-Thread
43*/
44static void tcpserv(void *arg)
45{
46 int ret;
47 char *recv_data; /* recv_data is a pointer used to receive data */ /* 用于接收的指针,后面会做一次动态分配以请求可用内存 */
48 int sock, connected, bytes_received;
49 struct sockaddr_in server_addr, client_addr;
50
51 struct timeval timeout;
52 fd_set readset, readset_c;
53 socklen_t sin_size = sizeof(struct sockaddr_in);
54
55 recv_data = rt_malloc(BUFSZ + 1);/* Allocate space for recv_data */ /* 分配接收用的数据缓冲 */
56 if (recv_data == RT_NULL)
57 {
58 LOG_E("No memory");
59 return;
60 }
61 /* Before making use of socket, socket should be created first and set the socket created to SOCK_STREAM(TCP) */
62 /* 一个socket在使用前,需要预先创建出来,指定SOCK_STREAM为TCP的socket */
63 if ((sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1)
64 {
65 LOG_E("Create socket error");
66 goto __exit;
67 }
68 /* Initialize server side address */
69 /* 初始化服务端地址 */
70 server_addr.sin_family = AF_INET;
71 server_addr.sin_port = htons(port); /*Server side port number*//* 服务端工作的端口 */
72 server_addr.sin_addr.s_addr = INADDR_ANY;
73 rt_memset(&(server_addr.sin_zero), 0x0, sizeof(server_addr.sin_zero));
74 /* Bind socket to server side address */
75 /* 绑定socket到服务端地址 */
76 if (bind(sock, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1)
77 {
78 LOG_E("Unable to bind");
79 goto __exit;
80 }
81 /* Listen on socket */
82 /* 在socket上进行监听 */
83 if (listen(sock, 10) == -1)
84 {
85 LOG_E("Listen error");
86 goto __exit;
87 }
88
89 LOG_I("\nTCPServer Waiting for client on port %d...\n", port);
90
91 started = 1;
92 is_running = 1;
93
94 timeout.tv_sec = 3;
95 timeout.tv_usec = 0;
96
97 while (is_running)
98 {
99 FD_ZERO(&readset);
100 FD_SET(sock, &readset);
101

Callers

nothing calls this directly

Calls 12

rt_mallocFunction · 0.85
socketFunction · 0.85
rt_memsetFunction · 0.85
bindFunction · 0.85
listenFunction · 0.85
acceptFunction · 0.85
closesocketFunction · 0.85
sendFunction · 0.85
rt_strlenFunction · 0.85
rt_freeFunction · 0.85
selectFunction · 0.50
recvFunction · 0.50

Tested by

no test coverage detected