STM32F103固件库在建立tcp客户端,在数据接收回调函数将数据一个一个写入ringbuffer,数据接收回调函数代码
时间: 2024-03-10 16:44:49 浏览: 142
TCP 接收数据
以下是一个简单的TCP客户端接收数据的回调函数代码示例,其中数据一个一个写入ringbuffer:
```
#include "lwip/api.h"
#define RX_BUF_SIZE 1024
#define RING_BUF_SIZE 4096
static uint8_t rx_buf[RX_BUF_SIZE];
static uint16_t rx_len = 0;
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;
}
// Copy data to receive buffer
uint16_t len = pbuf_copy_partial(p, rx_buf + rx_len, RX_BUF_SIZE - rx_len, 0);
rx_len += len;
// Check if we received all expected data
if (rx_len >= EXPECTED_LEN) {
// Write data to ring buffer
uint16_t space_left = RING_BUF_SIZE - ring_head + ring_tail;
if (rx_len > space_left) {
// Not enough space in ring buffer, discard oldest data
uint16_t discard_len = rx_len - space_left;
ring_tail = (ring_tail + discard_len) % RING_BUF_SIZE;
}
uint16_t write_len = (rx_len < space_left) ? rx_len : space_left;
uint16_t first_write_len = (write_len <= (RING_BUF_SIZE - ring_head)) ? write_len : (RING_BUF_SIZE - ring_head);
memcpy(ring_buf + ring_head, rx_buf, first_write_len);
memcpy(ring_buf, rx_buf + first_write_len, write_len - first_write_len);
ring_head = (ring_head + write_len) % RING_BUF_SIZE;
// Reset receive buffer
rx_len = 0;
}
// Free received pbuf
pbuf_free(p);
}
```
在该函数中,我们首先检查是否收到了数据。如果没有收到数据,则关闭TCP连接并返回。如果收到了数据,我们将数据复制到接收缓冲区中,并增加接收长度。然后,我们检查是否已经接收到了所有期望的数据。如果是,我们将数据写入环形缓冲区中。我们首先计算环形缓冲区中剩余的空间,如果不足以存储所有的数据,则丢弃最旧的数据。然后,我们将数据从接收缓冲区中复制到环形缓冲区中。如果数据长度大于环形缓冲区中剩余的空间,则需要进行两次复制。最后,我们重置接收缓冲区并释放pbuf。
阅读全文