文章目录
1.前言
本篇文章主要是介绍在STM32平台上移植LwIP 2.1.2后,如何使用API进行TCP Server编程。
LwIP主要提供了3种方式编程:
- RAW API:直接访问核心的lwIP栈。优点:不存在数据多次拷贝,占用内存小。缺点:调用RAW API相对比较繁琐,移植性差。
- Netconn API:调用RAW API访问核心的lwIP栈。优点:简化RAW API繁琐的调用。缺点:不通用其他平台API,移植性差。
- Socket API:通过BSD socket风格的接口访问lwIP栈。优点:通用其它平台API,方便程序移植。缺点:存在数据多次拷贝,占用内存。
这3种方式编程的之间的关系如下图所示:
如果想了解如何移植LwIP2.1.2,可以参考这篇文章《【FreeRTOS】基于STM32移植LWIP 2.1.2详细步骤》。本篇文章只是介绍LwIP TCP API如何使用。
2.如何配置LwIP支持Netconn和Socket
需要在lwipopts.h
中,打开LWIP_NETCONN
和LWIP_SOCKET
这2个宏,如下:
/**
* LWIP_NETCONN==1: Enable Netconn API (require to use api_lib.c)
*/
#define LWIP_NETCONN 1
/*
------------------------------------
---------- Socket options ----------
------------------------------------
*/
/**
* LWIP_SOCKET==1: Enable Socket API (require to use sockets.c)
*/
#define LWIP_SOCKET 1
3.使用LwIP Netconn API实现TCP Server
LwIP Netconn API编程主要是6个步骤:
- 初始化netconn:
netconn_new
- 绑定本地的端口:
netconn_bind
- 设置Task进入监听模式:
netconn_listen
- 阻塞方式等待client连接:
netconn_accept
- 阻塞方式receive client的消息:
netconn_recv
- 调用
netconn_write
发送消息给TCP Client
具体实现的代码如下:
#include "main.h"
#include "tcp_server.h"
#include "lwip/opt.h"
#include "lwip/tcpip.h"
#include "lwip/sys.h"
#include "lwip/api.h"
#include "lwip/sockets.h"
#include "FreeRTOS.h"
#include "semphr.h"
#include "task.h"
#include "string.h"
#define LOCAL_PORT 7000
#define SERVER_PORT 6000
#define TCP_SERVER_TASK_PRIO ( tskIDLE_PRIORITY + 4 )
#define TCP_SERVER_STACK_SIZE ( configMINIMAL_STACK_SIZE * 4 )
static sys_thread_t lwip_thread;
#define RECV_BUF_SIZE 256
static uint8_t recvBuf[RECV_BUF_SIZE];
static struct netconn *tcp_server_handle = NULL;
boolean tcp_server_is_connected(void)
{
if(lwip_thread.thread_handle != NULL){
return TRUE;
}else{
return FALSE;
}
}
void tcp_server_disconnect(void)
{
struct netconn *conn = tcp_server_handle;
if(conn != NULL){
netconn_close(conn);
netconn_delete(conn);
vTaskDelete(lwip_thread.thread_handle);
lwip_thread.thread_handle = NULL;
}
}
int8_t tcp_server_send_data(uint8_t *pData, uint16_t len)
{
int8_t ret = -1;
struct netconn *conn = tcp_server_handle;
if(conn == NULL){
printf("tcp server is connect!!!\r\n");
return ret;
}
ret = netconn_write(conn, pData, len, NETCONN_COPY);
if (ret != ERR_OK) {
printf("tcpecho: netconn_write: error \"%s\"\n", lwip_strerr(ret));
}
return ret;
}
static void tcp_server_netconn_thread(void *arg)
{
struct netconn *conn, *newconn;
struct netbuf *buf;
err_t err;
LWIP_UNUSED_ARG(arg);
/* Bind to TCP Client port with default IP address */
conn = netconn_new(NETCONN_TCP);
if(conn == NULL){
printf("[TCP Client]netconn_new: invalid conn\r\n");
goto EXIT;
}
netconn_bind(conn, IP4_ADDR_ANY, LOCAL_PORT);
/* Tell connection to go into listening mode. */
err = netconn_listen(conn);
if(err != ERR_OK){
printf("[TCP Server]netconn_listen is fail!!!\r\n");
goto EXIT;
}
printf("[TCP Server] The Dev server init is successful!!!\r\n");
ACCEPT_AGAIN:
while(1){
/* Grab new connection. */
err = netconn_accept(conn, &newconn);
printf("accepted new connection %p\n", newconn);
if (err == ERR_OK) {
tcp_server_handle = newconn;
break;
}
}
do {
err = netconn_recv(newconn, &buf);
if (err == ERR_OK) {
uint8_t len = (buf->p->len < RECV_BUF_SIZE) ? buf->p->len : RECV_BUF_SIZE;
MEMCPY(recvBuf, buf->p->payload, len);
recvBuf[len] = '\0';
printf("[Recv Data]%s\r\n", (char *)recvBuf);
}else{
printf("The client is disconnect %p\n", tcp_server_handle);
netconn_close(tcp_server_handle);
netconn_delete(tcp_server_handle);
tcp_server_handle = NULL;
goto ACCEPT_AGAIN;
}
if (buf != NULL) {
netbuf_delete(buf);
}
} while (1);
EXIT:
vTaskDelete(lwip_thread.thread_handle);
lwip_thread.thread_handle = NULL;
return;
}
void tcp_server_init(void)
{
lwip_thread = sys_thread_new("tcp_server_netconn", tcp_server_netconn_thread, NULL, TCP_SERVER_STACK_SIZE, TCP_SERVER_TASK_PRIO);
}
4.使用LwIP Socket API实现TCP Server
LwIP Socket API编程主要是6个步骤:
- 创建Tcp Server Socket:
socket
- 绑定指定的IP和Port:
bind
- 设置socket为监听状态:
listen
- 阻塞方式等待client连接:
accept
- 阻塞方式receive client的消息:
recv
- 调用
send
发送消息给TCP Client
具体实现的代码如下:
#include "main.h"
#include "tcp_server.h"
#include "lwip/opt.h"
#include "lwip/tcpip.h"
#include "lwip/sys.h"
#include "lwip/api.h"
#include "lwip/sockets.h"
#include "FreeRTOS.h"
#include "semphr.h"
#include "task.h"
#include "string.h"
#define LOCAL_PORT 7000
#define SERVER_PORT 6000
#define TCP_SERVER_TASK_PRIO ( tskIDLE_PRIORITY + 4 )
#define TCP_SERVER_STACK_SIZE ( configMINIMAL_STACK_SIZE * 4 )
static sys_thread_t lwip_thread;
//调用socket函数返回的文件描述符
static int serverSocket = -1;
static int clientSocket = -1;
boolean tcp_server_is_connected(void)
{
if(serverSocket != -1){
return TRUE;
}else{
return FALSE;
}
}
void tcp_server_disconnect(void)
{
if(serverSocket != -1){
close(serverSocket);
serverSocket = -1;
vTaskDelete(lwip_thread.thread_handle);
lwip_thread.thread_handle = NULL;
}
}
int8_t tcp_server_send_data(uint8_t *pData, uint16_t len)
{
int8_t ret = -1;
if(clientSocket == -1){
return ret;
}
ret = send(clientSocket, pData, len, 0); //向客户端发送消息
if (ret < 0) {
printf("[TCP Client] Send data is error!!!\r\n");
}
return ret;
}
static void tcp_server_netconn_thread(void *arg)
{
//声明两个套接字sockaddr_in结构体变量,分别表示客户端和服务器
struct sockaddr_in server_addr;
struct sockaddr_in clientAddr;
int addr_len = sizeof(clientAddr);
char buffer[200]; //存储 发送和接收的信息
int iDataNum;
//socket函数,失败返回-1
//int socket(int domain, int type, int protocol);
//第一个参数表示使用的地址类型,一般都是ipv4,AF_INET
//第二个参数表示套接字类型:tcp:面向连接的稳定数据传输SOCK_STREAM
//第三个参数设置为0
//建立socket
if((serverSocket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP)) < 0)
{
printf("Tcp Server create socket is fail!!!\r\n");
goto EXIT;
}
//初始化 server_addr
memset(&server_addr,0, sizeof(server_addr));
//初始化服务器端的套接字,并用htons和htonl将端口和地址转成网络字节序
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(SERVER_PORT);
//ip可是是本服务器的ip,也可以用宏INADDR_ANY代替,代表0.0.0.0,表明所有地址
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
//对于bind,accept之类的函数,里面套接字参数都是需要强制转换成(struct sockaddr *)
//bind三个参数:服务器端的套接字的文件描述符,
if(bind(serverSocket, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0)
{
printf("Tcp Server bind is fail!!!\r\n");
goto EXIT;
}
//设置服务器上的socket为监听状态
if(listen(serverSocket, 5) < 0)
{
printf("Tcp Server bind is fail!!!\r\n");
goto EXIT;
}
//循环 接收消息、发送消息
while(1)
{
printf("监听端口: %d\n", SERVER_PORT);
//调用accept函数后,会进入阻塞状态
//accept返回一个套接字的文件描述符,这样服务器端便有两个套接字的文件描述符,
//serverSocket和client。
//serverSocket仍然继续在监听状态,client则负责接收和发送数据
//clientAddr是一个传出参数,accept返回时,传出客户端的地址和端口号
//addr_len是一个传入-传出参数,传入的是调用者提供的缓冲区的clientAddr的长度,以避免缓冲区溢出。
//传出的是客户端地址结构体的实际长度。
//出错返回-1
clientSocket = accept(serverSocket, (struct sockaddr*)&clientAddr, (socklen_t*)&addr_len);
if(clientSocket < 0)
{
printf("Tcp Server accept is fail!!!\r\n");
continue;
}
printf("等待消息...\n");
//inet_ntoa ip地址转换函数,将网络字节序IP转换为点分十进制IP
//表达式:char *inet_ntoa (struct in_addr);
printf("IP is %s\n", inet_ntoa(clientAddr.sin_addr)); //把来访问的客户端的IP地址打出来
printf("Port is %d\n", htons(clientAddr.sin_port));
while(1)
{
buffer[0] = '\0';
iDataNum = recv(clientSocket, buffer, 1024, 0);
if(iDataNum < 0)
{
continue;
}
buffer[iDataNum] = '\0';
printf("收到消息: %s\n", buffer);
}
}
EXIT:
vTaskDelete(lwip_thread.thread_handle);
lwip_thread.thread_handle = NULL;
return;
}
void tcp_server_init(void)
{
lwip_thread = sys_thread_new("tcp_server_netconn", tcp_server_netconn_thread, NULL, TCP_SERVER_STACK_SIZE, TCP_SERVER_TASK_PRIO);
}
5.验证测试
最后验证测试成功,如下:
6.资料下载地址
移植成功的完整代码下载地址如下:
https://download.csdn.net/download/ZHONGCAI0901/13625345