STEP1:TCP服务器的建立
标准的简易TCP服务器模型包括:
服务器的初始化;
服务器对客户端连接的接受部分;
服务器的回复部分;
平台:STM32F767开发板
需要工具:
花生壳电脑客户端
手机端的TCP(我用的是Iphone的“网络”可以在Apple Store找到)
接下来是我服务器的代码tcp_server.h
这段代码的目的就是生成一个TCP服务器后可以通过客户端连接并给服务器发送LED0ON和LED0OFF来实现STM32LED的亮和灭LED1操作方法一致
#include "debug.h"
#include "stats.h"
#include "tcp.h"
#include "gpio.h"
#include "tcp_server.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
static err_t tcp_server_accept(void *arg, struct tcp_pcb *pcb, err_t err);
static err_t tcp_server_recv(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err);
char tcp_server_recvbuf[300]; //接受缓存
void Tcp_Server_Init(void) //TCP服务器的初始化
{
struct tcp_pcb *tcp_server_pcb;
tcp_server_pcb = tcp_new();
tcp_bind(tcp_server_pcb, IP_ADDR_ANY, 80);
tcp_server_pcb = tcp_listen(tcp_server_pcb);
tcp_accept(tcp_server_pcb, tcp_server_accept);
}
static err_t tcp_server_accept(void *arg, struct tcp_pcb *pcb, err_t err) //TCP服务器接受客户端连接
{
tcp_arg(pcb, mem_calloc(sizeof(struct name), 1));
tcp_write(pcb, "connect success£¡ \n\r",strlen("connect success£¡ \n\r "), 1);
tcp_recv(pcb, tcp_server_recv);
return ERR_OK;
}
static err_t tcp_server_recv(void *arg, struct tcp_pcb *pcb, struct pbuf *tcp_recv_pbuf, err_t err) //TCP服务器回复以及进行相应操作
{
// struct pbuf *tcp_send_pbuf;
struct name *name = (struct name *)arg;
// int i;
if (tcp_recv_pbuf != NULL)
{
tcp_recved(pcb, tcp_recv_pbuf->tot_len);
if (!name)
{
pbuf_free(tcp_recv_pbuf);
return ERR_ARG;
}
memcpy(tcp_server_recvbuf,tcp_recv_pbuf->payload,tcp_recv_pbuf->len);
/*LED1操作指令*/
if(tcp_server_recvbuf[2]=='L'&tcp_server_recvbuf[3]=='E'&tcp_server_recvbuf[4]=='D'&
tcp_server_recvbuf[5]=='1'&tcp_server_recvbuf[6]=='O'&tcp_server_recvbuf[7]=='N')
{
HAL_GPIO_WritePin(GPIOB, DS1_Pin, GPIO_PIN_RESET);
tcp_write(pcb, "LED1已打开\n",strlen("LED1已打开\n"), 1);
}
if(tcp_server_recvbuf[2]=='L'&tcp_server_recvbuf[3]=='E'&tcp_server_recvbuf[4]=='D'&
tcp_server_recvbuf[5]=='1'&tcp_server_recvbuf[6]=='O'&tcp_server_recvbuf[7]=='F'&tcp_server_recvbuf[7]=='F')
{
HAL_GPIO_WritePin(GPIOB, DS1_Pin, GPIO_PIN_SET);
tcp_write(pcb, "LED1已关闭\n",strlen("LED1已关闭\n"), 1);
}
/*LED0操作指令*/
if(tcp_server_recvbuf[2]=='L'&tcp_server_recvbuf[3]=='E'&tcp_server_recvbuf[4]=='D'&
tcp_server_recvbuf[5]=='0'&tcp_server_recvbuf[6]=='O'&tcp_server_recvbuf[7]=='N')
{
HAL_GPIO_WritePin(GPIOB, DS0_Pin, GPIO_PIN_RESET);
tcp_write(pcb, "LED0已打开\n",strlen("LED0已关闭\n"), 1);
}
if(tcp_server_recvbuf[2]=='L'&tcp_server_recvbuf[3]=='E'&tcp_server_recvbuf[4]=='D'&
tcp_server_recvbuf[5]=='0'&tcp_server_recvbuf[6]=='O'&tcp_server_recvbuf[7]=='F'&tcp_server_recvbuf[7]=='F')
{
HAL_GPIO_WritePin(GPIOB, DS0_Pin, GPIO_PIN_SET);
tcp_write(pcb, "LED0已关闭\n",strlen("LED0已关闭\n"), 1);
}
tcp_write(pcb, "\n", strlen("\n"), 1);
pbuf_free(tcp_recv_pbuf);
}
else if (err == ERR_OK)
{
mem_free(name);
return tcp_close(pcb);
}
return ERR_OK;
}
|
|