下载 FreeRTOS
 

出色的 RTOS & 嵌入式软件

最新资讯
简化任何设备的身份验证云连接。
利用 CoAP 设计节能型云连接 IoT 解决方案。
11.0.0 版 FreeRTOS 内核简介:
FreeRTOS 路线图和代码贡献流程。
使用 FreeRTOS 实现 OPC-UA over TSN。

使用 TCP 套接字接收数据
FreeRTOS-Plus-TCP 网络教程节选

[注意: 本页不介绍供专家用户使用的回调或零拷贝接口 本页不做相关描述。]

FreeRTOS_recv() 用于从 TCP 套接字接收数据。 FreeRTOS_recv() 在创建、配置、绑定 TCP 套接字并将其连接到远程套接字后才能调用。

下述源代码演示了如何通过 FreeRTOS_recv() 将接收数据放入缓冲区。 在本示例中, 假设套接字已创建并连接。


#define BUFFER_SIZE 512
static void prvEchoClientRxTask( void *pvParameters )
{
Socket_t xSocket;
static char cRxedData[ BUFFER_SIZE ];
BaseType_t lBytesReceived;

/* It is assumed the socket has already been created and connected before
being passed into this RTOS task using the RTOS task's parameter. */

xSocket = ( Socket_t ) pvParameters;

for( ;; )
{
/* Receive another block of data into the cRxedData buffer. */
lBytesReceived = FreeRTOS_recv( xSocket, &cRxedData, BUFFER_SIZE, 0 );

if( lBytesReceived > 0 )
{
/* Data was received, process it here. */
prvProcessData( cRxedData, lBytesReceived );
}
else if( lBytesReceived == 0 )
{
/* No data was received, but FreeRTOS_recv() did not return an error.
Timeout? */

}
else
{
/* Error (maybe the connected socket already shut down the socket?).
Attempt graceful shutdown. */

FreeRTOS_shutdown( xSocket, FREERTOS_SHUT_RDWR );
break;
}
}

/* The RTOS task will get here if an error is received on a read. Ensure the
socket has shut down (indicated by FreeRTOS_recv() returning a -pdFREERTOS_ERRNO_EINVAL
error before closing the socket). */


while( FreeRTOS_recv( xSocket, pcBufferToTransmit, xTotalLengthToSend, 0 ) >= 0 )
{
/* Wait for shutdown to complete. If a receive block time is used then
this delay will not be necessary as FreeRTOS_recv() will place the RTOS task
into the Blocked state anyway. */

vTaskDelay( pdTICKS_TO_MS( 250 ) );

/* Note - real applications should implement a timeout here, not just
loop forever. */

}

/* Shutdown is complete and the socket can be safely closed. */
FreeRTOS_closesocket( xSocket );

/* Must not drop off the end of the RTOS task - delete the RTOS task. */
xTaskDelete( NULL );
}

Example using FreeRTOS_recv()


<< 返回 RTOS TCP 网络教程索引

Copyright (C) Amazon Web Services, Inc. or its affiliates. All rights reserved.