- #include <stdio.h>
- #include <unistd.h>
- #include "ohos_init.h"
- #include "cmsis_os2.h"
- #include <unistd.h>
- #include "hi_wifi_api.h"
- //#include "wifi_sta.h"
- #include "lwip/ip_addr.h"
- #include "lwip/netifapi.h"
- #include "lwip/sockets.h"
- #define SERVER_PORT_TCP 6666
- #define TCP_BACKLOG 10
- /* 在sock_fd 进行监听,在 new_fd 接收新的链接 */
- int sock_fd, new_fd;
- char recvbuf[512];
- char *buf = "hello! I'm server!";
- int tcp_demo(void)
- {
- /* 自己的地址信息 */
- struct sockaddr_in my_addr;
- /* 连接者的地址信息*/
- struct sockaddr_in their_addr;
- int sin_size;
- struct sockaddr_in *cli_addr;
- printf("%s %d rn", __FILE__, __LINE__);
- /* 1 、创建socket */
- if((sock_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
- {
- printf("%s %d rn", __FILE__, __LINE__);
- perror("socket is errorrn");
- exit(1);
- }
- /* 主机字节顺序 */
- /* 协议 */
- my_addr.sin_family = AF_INET;
- my_addr.sin_port = htons(6666);
- /* 当前IP 地址写入 */
- my_addr.sin_addr.s_addr = INADDR_ANY;
- /* 将结构体其余的都清零 */
- bzero(&(my_addr.sin_zero), 8);
- printf("%s %d rn", __FILE__, __LINE__);
- /* bind 绑定*/
- if(bind(sock_fd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1)
- {
- printf("%s %d rn", __FILE__, __LINE__);
- perror("bind is errorrn");
- exit(1);
- }
- printf("%s %d rn", __FILE__, __LINE__);
- /* 开始监听 */
- if(listen(sock_fd, TCP_BACKLOG) == -1)
- {
- perror("listen is errorrn");
- exit(1);
- }
- printf("%s %d rn", __FILE__, __LINE__);
- printf("start acceptn");
- /* accept() 循环 */
- while(1)
- {
- sin_size = sizeof(struct sockaddr_in);
- printf("%s %d rn", __FILE__, __LINE__);
- if((new_fd = accept(sock_fd, (struct sockaddr *)&their_addr, (socklen_t *)&sin_size)) == -1)
- {
- perror("accept");
- continue;
- }
- cli_addr = malloc(sizeof(struct sockaddr));
- printf("accept addrrn");
- if(cli_addr != NULL)
- {
- memcpy(cli_addr, &their_addr, sizeof(struct sockaddr));
- }
- //处理目标
- ssize_t ret;
-
- while(1)
- {
- printf("%s %d rn", __FILE__, __LINE__);
- if((ret = recv(new_fd, recvbuf, sizeof(recvbuf), 0)) == -1){
- printf("recv error rn");
- return -1;
- }
- printf("recv :rn");
- printf("%s", recvbuf);
- printf("rn");
- sleep(2);
- if((ret = send(new_fd, buf, strlen(buf) + 1, 0)) == -1)
- {
- perror("send : ");
- }
- sleep(2);
- }
-
- close(new_fd);
- return 0;
- }
- }
- void TCPExampleEntry(void)
- {
-
- tcp_demo();
- }
- SYS_RUN(TCPExampleEntry);
复制代码Hi3861的WIFI已经成功开启。通过串口调试ESP01s,可以连接WIFI,但是在连接TCP服务器时失败。