Home > Blockchain >  Read all data during single recv() method from a socket
Read all data during single recv() method from a socket

Time:02-01

I am trying to continuously read the data using socket programming. I use recv() which receives data on a socket. I store it in a buffer. recv() returns the number of bytes read. Following is the snippet:

while (true) {
        try {
            char buff[2048];
            int bytes = recv(sockfd, buff, 2048, 0);
            buff[bytes] = '\0';
            cout << strlen(buff) << endl;
            cout << bytes << endl;
            cout << "-------" << endl;
        } catch (const char *e) {
        }
    }

Following is the output of the code:

1
1204
-------
1
1390
-------
1
25
-------
1
1204
-------

The number of bytes received are correct through recv() method but I am not able to read the exact number of data. How can I read all the data captured during single recv() method?

CodePudding user response:

You need to pass proper flag to recv as in documentation. Basing on: https://man7.org/linux/man-pages/man2/recv.2.html there is flag MSG_WAITALL (since Linux 2.2) that do what you want.

The call would look like:

int bytes = recv(sockfd, buff, 2048, MSG_WAITALL);

And checking length of received bytes by strlen is bad unless you are sure you receive only text.

CodePudding user response:

You can create a std::string_view pointing at the data read.

while (true) {
    char buff[2048];
    int bytes = recv(sockfd, buff, 2048, 0);
    if (bytes >= 0) {
        std::string_view read { buff, bytes };
        std::cout << read << std::endl;
        std::cout << "-------" << std::endl;
    } // else?
}
  •  Tags:  
  • Related