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

Function tcp_senddata

examples/network/tcpsendpacket.c:15–82  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

13#include <sys/socket.h> /* 使用BSD socket,需要包含socket.h头文件 */
14
15void tcp_senddata(const char *url, int port, int length)
16{
17 struct hostent *host;
18 int sock, err, result, timeout, index;
19 struct sockaddr_in server_addr;
20 rt_uint8_t *buffer_ptr;
21
22 /* 通过函数入口参数url获得host地址(如果是域名,会做域名解析) */
23 host = gethostbyname(url);
24 /* 创建一个socket,类型是SOCKET_STREAM,TCP类型 */
25 if ((sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1)
26 {
27 /* 创建socket失败 */
28 rt_kprintf("Socket error\n");
29 return;
30 }
31
32 /* 申请内存 */
33 buffer_ptr = rt_malloc(length);
34 if(RT_NULL == buffer_ptr)
35 {
36 /* 申请内存失败 */
37 rt_kprintf("No memory\n");
38 return;
39 }
40
41 /* 构造发送数据 */
42 for (index = 0; index < length; index ++)
43 buffer_ptr[index] = index & 0xff;
44
45 timeout = 100;
46 /* 设置发送超时时间100ms */
47 setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout));
48 /* 初始化预连接的服务端地址 */
49 server_addr.sin_family = AF_INET;
50 server_addr.sin_port = htons(port);
51 server_addr.sin_addr = *((struct in_addr *)host->h_addr);
52 rt_memset(&(server_addr.sin_zero), 0, sizeof(server_addr.sin_zero));
53
54 /* 连接到服务端 */
55 err = connect(sock, (struct sockaddr *)&server_addr, sizeof(struct sockaddr));
56 rt_kprintf("TCP thread connect error code: %d\n", err);
57
58 while (1)
59 {
60 /* 发送数据到sock连接 */
61 result = send(sock, buffer_ptr, length, MSG_DONTWAIT);
62 if (result < 0) //数据发送错误处理
63 {
64 rt_kprintf("TCP thread send error: %d\n", result);
65 closesocket(sock);
66
67 /* 关闭连接,重新创建连接 */
68 rt_thread_delay(10);
69
70 if ((sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1)
71 rt_kprintf("TCP Socket error:%d\n", sock);
72

Callers

nothing calls this directly

Calls 10

gethostbynameFunction · 0.85
socketFunction · 0.85
rt_kprintfFunction · 0.85
rt_mallocFunction · 0.85
setsockoptFunction · 0.85
rt_memsetFunction · 0.85
connectFunction · 0.85
sendFunction · 0.85
closesocketFunction · 0.85
rt_thread_delayFunction · 0.85

Tested by

no test coverage detected