STM32F103固件库在建立tcp客户端,在数据接收回调函数将数据一个一个写入环形缓冲区,数据接收回调函数代码
时间: 2024-03-10 13:44:51 浏览: 63
TCP 接收数据
以下是一个简单的TCP客户端接收数据的回调函数代码示例,其中数据一个一个写入环形缓冲区:
```
#include "lwip/api.h"
#define RX_BUF_SIZE 1
#define RING_BUF_SIZE 4096
static uint8_t rx_buf[RX_BUF_SIZE];
static uint8_t ring_buf[RING_BUF_SIZE];
static uint16_t ring_head = 0;
static uint16_t ring_tail = 0;
void tcp_client_recv_callback(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err) {
if (p == NULL) {
printf("TCP client connection closed.\n");
tcp_close(pcb);
return;
}
// Process each byte of received data
for (uint16_t i = 0; i < p->tot_len; i++) {
uint8_t byte = *((uint8_t*)p->payload + i);
// Write byte to ring buffer
uint16_t next_head = (ring_head + 1) % RING_BUF_SIZE;
if (next_head == ring_tail) {
// Ring buffer full, discard oldest byte
ring_tail = (ring_tail + 1) % RING_BUF_SIZE;
}
ring_buf[ring_head] = byte;
ring_head = next_head;
}
// Free received pbuf
pbuf_free(p);
}
```
在该函数中,我们首先检查是否收到了数据。如果没有收到数据,则关闭TCP连接并返回。如果收到了数据,我们将逐个字节地处理数据。对于每个字节,我们将其写入环形缓冲区中。如果环形缓冲区已满,则丢弃最旧的字节。最后,我们释放pbuf。
阅读全文