Home > database >  For a TCP server when does poll let you know when the socket is ready?
For a TCP server when does poll let you know when the socket is ready?

Time:10-16

Does poll give a POLLIN revent when the first TCP segment arrives or after the entire TCP message arrives? If the former is it possible that the first segment of a TCP message is sent, but not the complete message? How would the server handle that read so it won't block forever?

Edit: I've realized the solution to my problem if I wanted to persist with a TCP socket. I might try a SCTP socket instead. Seems to be more in line with how I want it to work.

CodePudding user response:

TCP is stream, not messages. So, pollin can be happened after any amount of data received

CodePudding user response:

Here is example how you can receive e.g. 1000 bytes from socket in conjunction with poll():

char buffer[MAX_MSG_SIZE];
char *p = buffer;
size_t bytes_left = 1000;   // Must be less or equal to MAX_MSG_SIZE

for (;;)
{
    int ret = poll(fds, num_fds, timeout);

    if (ret == -1) {
        // Handle poll() errors here
        // ...
        break;
    }
    if (ret == 0) {
        // Handle timeout here
        // ...
        continue;
    }

    if (fds[0].revents & POLLIN)    // Assume socket descriptor is in fds[0].fd
    {
        ssize_t len = recv(fds[0].fd, p, bytes_left, 0);

        if (len == -1) {
            // Handle recv() errors here
            // ...
        }

        bytes_left -= len;
        p  = len;

        if (bytes_left == 0) {
            // Do something with 1000 bytes in buffer
            // ...

            // Read next "message", e.g. 500 bytes
            bytes_left = 500;
            p = buffer;
        }
    }

    // Handle other fds events
    // ...
}
  • Related