1 /*
2 Copyright (C) 2024 HiHope Open Source Organization .
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6
7 http://www.apache.org/licenses/LICENSE-2.0
8
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 */
15
16 #include <stdio.h>
17 #include <unistd.h>
18 #include <string.h>
19 #include "lwip/sockets.h"
20 #include "osal_debug.h"
21 #include "oled_ssd1306.h"
22
23 static char request[50] = "test_data";
24 static char response[100] ;
25 static char display_data[11];
26
27 /* @brief TCP客户端测试函数
28 @param1 host TCP服务端IP地址
29 @param2 port TCP服务端端口
30 */
TcpClientTest(const char * host,unsigned short port)31 void TcpClientTest(const char *host, unsigned short port)
32 {
33 ssize_t ret = 0;
34 int c = 1;
35 // 创建一个TCP Socket
36 int sockfd = socket(AF_INET, SOCK_STREAM, 0);
37
38 // 设置服务端的地址信息
39 struct sockaddr_in serverAddr = {0};
40
41 // 设置服务端的信息
42 serverAddr.sin_family = AF_INET; // 使用IPv4协议
43 serverAddr.sin_port = htons(port); // 端口号
44
45 // 将服务端IP地址转化为标准格式
46 if (inet_pton(AF_INET, host, &serverAddr.sin_addr) <= 0)
47 {
48 // 转化失败
49 printf("inet_pton failed!\r\n");
50 // 关闭连接
51 closesocket(sockfd);
52 }
53
54 // 建立连接
55 if (connect(sockfd, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) < 0)
56 {
57 // 连接失败
58 printf("connect tcp server failed!\r\n");
59 OledShowString(0, 2, " ", FONT6x8);
60 OledShowString(0, 2, "conn tcp failed", FONT6x8);
61 // 关闭连接
62 closesocket(sockfd);
63 }
64
65 // 连接成功
66 printf("connect to tcp server %s success!\r\n", host);
67 // OLED显示服务端IP地址
68
69 OledShowString(0, 2, "conn tcp success", FONT6x8);
70 OledShowString(0, 4, "tcp server ip:", FONT6x8);
71 OledShowString(0, 5, host, FONT6x8);
72
73 // 发送数据
74 ret = send(sockfd, request, sizeof(request), 0);
75
76 // 检查接口返回值,小于0表示发送失败
77 if (ret < 0)
78 {
79 // 发送失败
80 printf("send request failed!\r\n");
81 }
82
83 // 发送成功
84 printf("send request{%s} %ld to tcp server !\r\n", request, ret);
85
86 while (c)
87 {
88 memset(display_data,0,strlen(display_data));
89 memset(response,0,strlen(response));
90 // 接收收据
91 ret = recv(sockfd, response, sizeof(response), 0);
92
93 // 接收失败或对方的通信端关闭
94 if (ret <= 0) {
95 printf(" recv_data failed or done, %ld!\r\n", ret);
96 }
97
98 // 接收成功,输出日志,OLED显示收到的收据,最多显示10个字符
99 printf(" recv_data{%s} from client!\r\n", response);
100 OledShowString(0, 7,"recv:", FONT6x8);
101 OledShowString(40, 7," ", FONT6x8);
102
103
104 memcpy(display_data,response,10);
105 display_data[11] = '\0';
106
107 OledShowString(40, 7,display_data, FONT6x8);
108 osDelay(100);
109
110 }
111
112
113 // 关闭socket
114 // closesocket(sockfd);
115 }
116