如何添加lwip参照上一篇 stm32CubeMx lwip + freeRTOS
今天讲一下,如何添加TCP服务
LwIP 提供了三种编程接口,分别为 RAW/Callback API、NETCONN API、SOCKET API。它们的易用性从左到右依次提高,而执行效率从左到右依次降低,用户可以根据实际情况,平衡利弊,选择合适的 API 进行网络应用程序的开发。这里介绍的是socket API接口的使用。
主要代码如下
服务器端
#define PORT 5001
#define RECV_DATA 1024
void StartDefaultTask(void const * argument)
{
/* init code for LWIP */
MX_LWIP_Init();
/* Infinite loop */
int sock = -1, connected;
char *recv_data;
struct sockaddr_in server_addr, client_addr;
socklen_t sin_size;
int recv_data_len;
recv_data = (char *)pvPortMalloc(RECV_DATA);
if(recv_data == NULL)
{
printf("No memory\n");
goto __exit;
}
sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock < 0)
{
printf("socket error\n");
}
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(PORT);
memset(&(server_addr.sin_zero), 0, sizeof(server_addr.sin_zero));
if(bind(sock, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1)
{
printf("unable to bind\n");
goto __exit;
}
listen(sock, 5);
while(1)
{
sin_size = sizeof(struct sockaddr_in);
connected = accept(sock, (struct sockaddr *)&client_addr, &sin_size);
printf("new client connected from %s, %d\r\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
{
int flag = 1;
setsockopt(connected, IPPROTO_TCP, TCP_NODELAY, (void *)&flag, sizeof(int));
}
while(1)
{
recv_data_len = recv(connected, recv_data, RECV_DATA, 0);
if(recv_data_len <= 0)
break;
printf("recv %d len data\r\n", recv_data_len);
write(connected, recv_data, recv_data_len);
}
if(connected >= 0)
closesocket(connected);
connected = -1;
}
__exit:
if(recv_data) free(recv_data);
if(sock >= 0) closesocket(sock);
vTaskDelete(defaultTaskHandle);
}
实验结果:
开发板烧写,网线连接电脑,开发板IP为192.168.1.21, 电脑IP地址设置为192.168.1.10
打开TCPUDP调试工具,创建TCP客户端,连接服务器,端口 5001
向开发板发送 hello world, 收到开发板发送回的hello world
客户端
#define PORT 5001
#define IP_ADDR "192.168.1.10"
{
int sock = -1;
struct sockaddr_in client_addr;
uint8_t send_buf[] = "This is a TCP client test \r\n";
while(1)
{
sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock < 0)
{
osDelay(10);
continue;
}
client_addr.sin_family = AF_INET;
client_addr.sin_port = htons(PORT);
client_addr.sin_addr.s_addr = inet_addr(IP_ADDR);
memset(&(client_addr.sin_zero), 0, sizeof(client_addr.sin_zero));
if(connect(sock, (struct sockaddr*)&client_addr, sizeof(struct sockaddr)) == -1)
{
printf("connect failed \r\n");
closesocket(sock);
osDelay(10);
continue;
}
printf("connect to iperf server successful!\n");
while(1)
{
if(write(sock, send_buf, sizeof(send_buf)) < 0)
break;
osDelay(10);
}
closesocket(sock);
}
}