Download FreeRTOS

Quality RTOS & Embedded Software

Simplifying Authenticated Cloud Connectivity for Any Device.
Designing an energy efficient and cloud-connected IoT solution with CoAP.
Introducing FreeRTOS Kernel version 11.0.0:
FreeRTOS Roadmap and Code Contribution process.
OPC-UA over TSN with FreeRTOS.

Receiving Data Using a TCP Socket
Part of the FreeRTOS-Plus-TCP Networking Tutorial

[Note: This page does not describe the callback or zero copy interfaces, which are available for expert users.]

FreeRTOS_recv() is used to receive data from a TCP socket. FreeRTOS_recv() cannot be called until the TCP socket has been created, configured, bound and connected to a remote socket.

The source code below demonstrates how to use FreeRTOS_recv() to place received data into a buffer. In the example it is assumed that the socket has already been created and connected.

#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? */

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

FreeRTOS_shutdown( xSocket, FREERTOS_SHUT_RDWR );

/* 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()

<< Back to the RTOS TCP networking tutorial index

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