基于STM32H750XBH6开发板搭建HTTP服务器
目录1 前言2 实现2.1 实现方法2.2 代码1 前言上一章实现了开发板做客户端访问HTTP服务端参见基于STM32H750XBH6开发板实现HTTP访问本章用STM32H7开发板实现一个基础HTTP静态页面服务器。2 实现2.1 实现方法本文基于LwIP协议栈的NETCONN API实现了一个轻量级的嵌入式HTTP Web服务核心功能如下1独立服务线程创建在初始化阶段创建一个专属的网络任务线程避免阻塞主程序或其他业务逻辑。2TCP 服务器监听绑定本地 IP 和 80 端口进入无限循环等待客户端如浏览器的连接请求。3HTTP 请求解析与响应接收客户端数据后简单判断是否为 HTTP GET 请求。如果是则向客户端发送标准的 HTTP 响应头和预设的网页内容包含文本、链接和图片。4连接生命周期管理在处理完单次请求后主动关闭并清理网络连接资源防止内存泄漏。2.2 代码先看代码注意链接可以自己修改#includelwip/opt.h#includelwip/arch.h#includelwip/api.h#includehttpserver-netconn.h#ifLWIP_NETCONN#ifndefHTTPD_DEBUG#defineHTTPD_DEBUGLWIP_DBG_OFF#endifstaticconstcharhttp_html_hdr[]HTTP/1.1 200 OK\r\nContent-type: text/html\r\n\r\n;staticconstcharhttp_index_html[]htmlheadtitleCongrats!/title/head\ bodyh1 align\center\Hello World!/h1\ h2 align\center\Welcome to HuanHai lwIP HTTP Server!/h2\ p align\center\This is a small test page, served by httpserver-netconn./p\ p align\center\a href\http://www.huantaibbs.cn/forum.php/\\ font size\6\ 环海电子论坛 /font /a/p\ a href\http://www.huantaibbs.cn/forum.php/\\ p align\center\img src\http://www.huantaibbs.cn/data/attachment/portal/\ 201806/05/163015rhz7mbgbt0zfujzh.jpg\ //a\ /body/html;/** Serve one HTTP connection accepted in the http thread */staticvoidhttp_server_netconn_serve(structnetconn*conn){structnetbuf*inbuf;char*buf;u16_tbuflen;err_terr;/* 读取数据 */errnetconn_recv(conn,inbuf);if(errERR_OK){netbuf_data(inbuf,(void**)buf,buflen);/* 判断是不是 HTTP 的 GET 命令*/if(buflen5buf[0]Gbuf[1]Ebuf[2]Tbuf[3] buf[4]/){/* 发送数据头 */netconn_write(conn,http_html_hdr,sizeof(http_html_hdr)-1,NETCONN_NOCOPY);/* 发送网页数据 */netconn_write(conn,http_index_html,sizeof(http_index_html)-1,NETCONN_NOCOPY);}}netconn_close(conn);/* 关闭连接 *//* 释放 inbuf */netbuf_delete(inbuf);}/** The main function, never returns! */staticvoidhttp_server_netconn_thread(void*arg){structnetconn*conn,*newconn;err_terr;LWIP_UNUSED_ARG(arg);/* 创建 netconn 连接结构 *//* 绑定端口号与 IP 地址端口号默认是 80 */connnetconn_new(NETCONN_TCP);netconn_bind(conn,IP_ADDR_ANY,80);LWIP_ERROR(http_server: invalid conn,(conn!NULL),return;);/* 监听 */netconn_listen(conn);do{//处理连接请求errnetconn_accept(conn,newconn);if(errERR_OK){//发送网页数据http_server_netconn_serve(newconn);//删除连接结构netconn_delete(newconn);}}while(errERR_OK);//关闭netconn_close(conn);netconn_delete(conn);}/** Initialize the HTTP server (start its thread) */voidhttp_server_netconn_init(void){sys_thread_new(http_server_netconn,http_server_netconn_thread,NULL,2048,4);}#endif// 头文件#ifndefLWIP_HTTPSERVER_NETCONN_H#defineLWIP_HTTPSERVER_NETCONN_Hvoidhttp_server_netconn_init(void);#endif