UDP socket non-blocking

Spooney
Posts: 7
Joined: Sun Jul 08, 2018 12:00 pm

UDP socket non-blocking

Postby Spooney » Sun Jul 08, 2018 12:16 pm

Hi

I am trying to use a UDP socket to both send and receive to another device. The port is known at the outset but the IP of the remote device is not.

My code sort of works in that if I send to the esp32 I can see what I sent on the uart output,, and an 'ACK' is received back from the esp32.

But I can't send correctly as the UDP socket blocks until I send something to it again. So I would have to keep sending something to the esp32 to get my data back.

When I set the dataReady to true nothing is sent until I send it something then I will get the ACK back and my test data.. Then nothing til I send again

I have tried setting the socket to non-blocking but I can't get that to works

int err = setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char*) &read_timeout, sizeof read_timeout);
also tried
int err = setsockopt(s, IPPROTO_UDP, SO_RCVTIMEO, (char*) &read_timeout, sizeof read_timeout);

This is probably something stupid but can't see it at the moment.

help would be much appreciated.

Full UDP-rec.c is attached

Thanks

Spooney
Attachments
UDP_rec.c
(3.46 KiB) Downloaded 813 times

jcsbanks
Posts: 305
Joined: Tue Mar 28, 2017 8:03 pm

Re: UDP socket non-blocking

Postby jcsbanks » Mon Jul 09, 2018 7:23 am

Long shot from quick look on phone, but if \r and \n end up as two bytes in your string you might not be copying the null termination with length of 30? Might not matter of course.

Spooney
Posts: 7
Joined: Sun Jul 08, 2018 12:00 pm

Re: UDP socket non-blocking

Postby Spooney » Mon Jul 09, 2018 9:53 am

Hi

Thanks for the suggestion but i don't think it is that. The data is just some I put there for testing.

I have attached a text file of the uart output and the output screen from the sender PC.

You can see the data but it is only sent the once when I send 'hello' to the esp32. It should have been sent at least 3 times if the data was sent when data was ready.

Thanks

Spooney
Attachments
uart output.txt
(525 Bytes) Downloaded 741 times

glrtheil
Posts: 61
Joined: Tue Dec 07, 2021 2:48 pm

Re: UDP socket non-blocking

Postby glrtheil » Tue Mar 15, 2022 2:34 am

I replied to another post about this, but I'll put it here as well for those searching for the answer.

In this example, the delay is 1ms (1000us). I'm looking to only process what might be in an rx buffer. It is necessary to set tv_sec to 0 in order to set something lower than 1 second.

Code: Select all

//make receive calls nonblocking
struct timeval tm;
tm.tv_sec = 0;
tm.tv_usec = 1000;

int err = setsockopt(_sock, SOL_SOCKET, SO_RCVTIMEO, &tm, sizeof(tm));
if (err < 0)
{
    ESP_LOGE(TAG, "setsockopt failed. error: %d", err);
}

Who is online

Users browsing this forum: No registered users and 176 guests