Now that we know the protocol, we can show how DistWebArray was implemented. Let's start with the implementation of the subscripting operator.
Document* DistWebArray::operator[](const RWCString& s) { RWPortalStreambuf sbuf(RWSocketPortal(this->addr_)); //1 RWvostream& ostrm = RWpostream(&sbuf); RWvistream& istrm = RWpistream(&sbuf); ostrm << RWCString("find") << s << flush; //2 Document *web; istrm >> web; //3 return web; }
//1 | Create the virtual streams ostrm and istrm for communication with the server. Both virtual streams use as a streambuf an RWPortalStreambuf connected to the server. Since this is a one-shot protocol, we must reconnect to the server for each request.
Why use this->addr_ instead of just addr_? Without this-> the compiler thinks this is a declaration of a function called sbuf that takes an RWSocketPortal named addr_ as a parameter! |
//2 | Make the request, according to the protocol we have defined. If we forget to flush the streambuf's buffer by inserting flush, the request will not get sent, the server will not reply, and the extraction operator on line (//3) will cause deadlock. |
//3 | Extract the web which the server has sent as its reply. |
The implementation of the insertion operation is just as straightforward. Here is the code.
void DistWebArray::insertKeyAndValue( const RWCString& s, Document* doc) { RWPortalStreambuf sbuf(RWSocketPortal(this->addr_)); //1 RWvostream& ostrm = RWpostream(&sbuf); RWvistream& istrm = RWpistream(&sbuf); ostrm << RWCString("insert") << s << doc << flush; //2 RWCString response; istrm >> response; //3 if (response!="ok") { throw RWExternalErr("insertKeyAndValue protocol failure"); } }
//1 | As before, set up a pair of streams for communicating with the server. |
//2 | Request insertion of the web, according to the protocol we defined. |
//3 | The protocol stipulates that the string "ok" is returned if all went well. Check that this string is actually returned. If it isn't, then throw an exception. |
©Copyright 2000, Rogue Wave Software, Inc.
Contact Rogue Wave about documentation or support issues.