#Best way to receive the information of udp sockets with rcvfrom

7 messages · Page 1 of 1 (latest)

jagged jacinth
#

I have my udp socket connection working correctly, but im facing a problem that when i receive more bytes that my buffer can store i dont have the full info. I have tried to make a while loop but i stay on teh rcvfrom after receiving the entire message.
The codes:

    string server_response;
    socklen_t addrlen = sizeof(addr); // na folha tava int addrlen

    char temp_server_response[BUFFER_SIZE];
    n = recvfrom(fd, temp_server_response, BUFFER_SIZE, 0, (struct sockaddr *) &addr, &addrlen);
    if (n == -1) {
        exit(1); // Dizer ao user q a ligacao udp errou
    } else if (n == 0) {
        exit(1); // pensar neste caso
    } else  {
        server_response += string(temp_server_response, n);
    }
    string server_response;
    socklen_t addrlen = sizeof(addr); // na folha tava int addrlen
    do {
        char temp_server_response[BUFFER_SIZE];
        n = recvfrom(fd, temp_server_response, BUFFER_SIZE, 0, (struct sockaddr *) &addr, &addrlen);
        if (n == -1) {
            exit(1); // Dizer ao user q a ligacao udp errou
        } else if (n == 0) {
            exit(1); // pensar neste caso
        } else {
            server_response += string(temp_server_response, n);
        }

    } while (n == BUFFER_SIZE);

safe zenithBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

jagged jacinth
#

i am actually using a c library so thats why i have some cpp code like the std:string and my question is in this chat, but consider that this variable simply stores the buffers so that i can reset it and get more bytes from the rcvfrom

quaint spear
#

Where is the first code block from, and where is the second from? They almost seem identical

#

One issue with your while (n == BUFFERSIZE) condition is that assumes that recvfrom() will always return BUFFERSIZE as long as you are reading the start and middle of the message. The function however often will return less than the BUFFERSIZE in reality, so instead you want to continue calling the function as long as n > 0

#

It is not an error if this number is smaller than the number of bytes requested; this may happen for example because fewer bytes are actually available right now

#

Also, keep in mind that if you are trying to for example read a HTTP GET request, it's your server's responsibility to detect that it should stop calling recvfrom() once you've read content_length bytes from the header.

So in other words, it's your server's responsibility to stop calling recvfrom() when you've read enough.