PREV UP next C++ socket classes for OS/2

3.6: Time Outs While Reading and Writing

Time outs are very useful in handling data of unknown sizes and formats while reading and writing. For example, how does one communicate with a socket that sends chunks of data of unknown size and format? If only sockbuf::read is used without time out, it will block indefinitely. In such cases, time out facility is the only answer.

The following idiom is recommended. See Pitfalls for a complete example.


    int old_tmo = s.recvtimeout (2) // set time out (2 seconds here)

    for (;;) { // read or write

        char buf[256];

        int rval = s.read (buf, 256);

        if (rval == 0 || rval == EOF) break;

        // process buf here

    }

    s.recvtimeout (old_tmo); // reset time out

In what follows,

s.recvtimeout(wp)
sets the recv timeout to wp seconds. If wp is -1, it is a block and if wp is 0, it is a poll.

It affects all read functions. If the socket is not read ready within wp seconds, the read call will return 0. It also affects sockbuf::underflow. sockbuf::underflow will not set the _S_EOF_SEEN flag if it is returning EOF because of timeout.

sockbuf::recvtimeout returns the old recv timeout value.

s.sendtimeout(wp)
sets the send timeout to wp seconds. If wp is -1, it is a block and if wp is 0, it is a poll.

It affects all write functions. If the socket is not write ready within wp seconds, the write call will return 0.

sockbuf::sendtimeout returns the old send timeout value.