Article Directory
1 Introduction
This article mainly introduces porting on the STM32 platformLwIP 2.1.2Later, how to use API for TCP Server programming.
LwIP mainly provides 3 ways to program:
- RAW API : Directly access the core lwIP stack. Advantages : There is no multiple copies of data and small memory usage. Disadvantages : calling RAW API is relatively cumbersome and poor in portability.
- Netconn API : Call RAW API to access the core lwIP stack. Advantages : simplify the tedious call of RAW API. Disadvantages : Not common to other platform APIs, poor portability.
- Socket API : Access the lwIP stack through a BSD socket style interface. Advantages : Common other platform APIs, convenient for program transplantation. Disadvantages : There are multiple copies of data, which takes up memory.
The relationship between these 3 ways of programming is shown in the figure below:
If you want to know how to transplant LwIP 2.1.2, you can refer to this article "[FreeRTOS] Detailed steps for transplanting LWIP 2.1.2 based on STM32" . This article only introduces how to use LwIP TCP API.
2. How to configure LwIP to support Netconn and Socket
Need lwipopts.h
to open LWIP_NETCONN
and LWIP_SOCKET
these 2 macros in the middle , as follows:
/**
* 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. Use LwIP Netconn API to implement TCP Server
LwIP Netconn API programming mainly consists of 6 steps:
- Initialize netconn:
netconn_new
- Bind the local port:
netconn_bind
- Set Task to enter monitoring mode:
netconn_listen
- Waiting for client connection in blocking mode:
netconn_accept
- Receive client's message in blocking mode:
netconn_recv
- Call to
netconn_write
send message to TCP Client
The specific implementation code is as follows:
#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. Use LwIP Socket API to implement TCP Server
LwIP Socket API programming mainly consists of 6 steps:
- Create Tcp Server Socket:
socket
- Bind the specified IP and Port:
bind
- Set the socket to the listening state:
listen
- Waiting for client connection in blocking mode:
accept
- Receive client's message in blocking mode:
recv
- Call to
send
send message to TCP Client
The specific implementation code is as follows:
#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. Verification test
Finally, the verification test is successful, as follows:
6. Data download address
The complete code download address for successful transplantation is as follows:
https://download.csdn.net/download/ZHONGCAI0901/13625345