Chapter 10. WvStream - communications fundamentals

Table of Contents
Basic WvStream Examples
Reading and Writing
Waiting on a stream with select()
Callback Functions
Delays and Timeouts

WvStream is the base class from which (not surprisingly) most of the WvStreams library is derived. It defines the basic properties of a stream: a sequence of bytes that may or may not be ready for reading or writing at any given time.

WvStream is a perfectly useful class all by itself; it can read, write, and wait on a Unix fd (file descriptor), which is sufficient for nearly all communications in Unix-like systems. The other WvStream classes do basically the same thing, but create and manipulate their fds automatically instead of requiring you to do it.

Basic WvStream Examples

The following example program reads from stdin and echos the results back to stdout with a bit of added commentary. Remember that in Unix, fd 0 is stdin, and fd 1 is stdout.

	  
/* 
 * A WvStream example.
 *
 * Some documentation for WvStreams...
 */

#include <wvstream.h>

int main()
{
    while (wvin->isok())
	wvout->print("You said: %s\n", wvin->blocking_getline(-1));
}

 	 

isok() ("is okay") returns true as long as the stream is still alive. If you press CTRL-D as the input to a program, this sends an end-of-file message and the stream becomes "not okay." (isok() == false).

The getline() function reads a character string of arbitrary length using WvBuffer, up to but not including the first newline. The (-1) tells getline() to wait forever for the newline if necessary. Try changing it to 5000 (5 seconds) and see how that affects the operation of the program.

Whenever possible, WvStreams tries to shelter you from weird Unix-specific information like fd 0 and fd 1. There is a special WvStream pointer called wvcon which points to both stdin and stdout. (Actually, since it points at both fd 0 and fd 1, wvcon needs to be a WvSplitStream object, but don't worry about that just yet.)

You can reassign wvcon to any other stream if you like -- this will let you essentially redirect stdin and stdout for the WvStreams classes that use it.

Here's an example of how you can use wvcon to simplify the above sample program.

	  
/*
 * A WvStream example.
 *
 * Some text about this example...
 */

#include <wvstream.h>

int main()
{
    while (wvcon->isok())
	wvcon->print("You said: %s\n", wvcon->blocking_getline(-1));
}