LWIP配置
服务器端实现
客户端实现
错误分析
一。LWIP配置(FREERTOS配置,ETH配置,LWIP配置)
1.FREERTOS配置
为什么要修改定时源为Tim1?不用systick?
原因:HAL库与FREERTOS都需要使用systick,两者冲突,所以修改时钟源,让FREERTOS使用Tim1。
2.ETH配置
3.LWIP配置
不使用DHCP
4.步骤:
(1)freertos.c中会自己出现一个Lwip初始化
运行后结果:命令行中输入ping 192.168.1.10有回复
二。服务器端
1.功能分析
小写转大写
2.步骤:
(1)建立socket_tcp_server.h
#ifndef SOCKET_TCP_SERVER_H
#define SOCKET_TCP_SERVER_H#define SERVER_IP "192.168.1.11"
#define SERVER_PORT 6666
#define BUFF_SIZE 1024void vTcpServerTask(void);#endif
(2)建立socket_tcp_server.c,并添加到文件中
#include "socket_tcp_server.h"
#include "lwip/sockets.h"
#include "ctype.h"char ReadBuff[BUFF_SIZE];/*** @brief TCP 服务器任务* @param None* @retval None*/
void vTcpServerTask(void){int sfd, cfd, n, i;struct sockaddr_in server_addr, client_addr;socklen_t client_addr_len;//创建socketsfd = socket(AF_INET, SOCK_STREAM, 0);server_addr.sin_family = AF_INET;server_addr.sin_port = htons(SERVER_PORT);server_addr.sin_addr.s_addr = htonl(INADDR_ANY);//绑定socketbind(sfd, (struct sockaddr *)&server_addr, sizeof(server_addr));//监听socketlisten(sfd, 5);//等待客户端连接client_addr_len = sizeof(client_addr);cfd = accept(sfd, (struct sockaddr *)&client_addr, &client_addr_len);printf("client is connect cfd = %d\r\n",cfd);while(1){//等待客户端发送数据n = read(cfd, ReadBuff, BUFF_SIZE);//进行大小写转换for(i = 0; i < n; i++){ReadBuff[i] = toupper(ReadBuff[i]); }//写回客户端write(cfd, ReadBuff, n);}
}
(3)freertos.c中网络任务中,添加服务器运行函数。
不要忘记添加头文件
vTcpServerTask();
3.现象演示
(1)使用COMMBOX串口调试工程,添加socket网络客户端 ,目标ip为stm32的ip.端口在.h中
(2)stm32客户端发送的字母变大写
三。客户端创建
1.创建socket_tcp_client.c与socket_tcp_client.h
(1)socket_tcp_client.c
#include "socket_tcp_server.h"
#include "socket_tcp_client.h"
#include "lwip/sockets.h"
#include "ctype.h"static char ReadBuff[BUFF_SIZE];void vTcpClientTask(void)
{int cfd, n, i;struct sockaddr_in server_addr;//创建socketcfd = socket(AF_INET, SOCK_STREAM, 0);server_addr.sin_family = AF_INET;server_addr.sin_port = htons(SERVER_PORT);server_addr.sin_addr.s_addr = inet_addr(SERVER_IP);//连接到服务器connect(cfd, (struct sockaddr*)&server_addr, sizeof(server_addr));printf("server is connect ok\r\n");while(1){//等待服务器发送数据n = read(cfd, ReadBuff, BUFF_SIZE);//进行大小写转换for(i = 0; i < n; i++){ReadBuff[i] = toupper(ReadBuff[i]); }//写回服务器write(cfd, ReadBuff, n);}
}
(2)socket_tcp_client.h
#ifndef _SOCKET_TCP_CLIENT_H
#define _SOCKET_TCP_CLIENT_Hvoid vTcpClientTask(void);#endif