Here's our first implementation of the greeting server. It uses the sequential strategy for handling calls. This first implementation is too simple for real use, and is not included in the net library distribution.
int main() { try { // 1 RWWinSockInfo info; static RWCString greeting = "It's my first time. Honest"; // 2 RWSocketListener listener( RWInetAddr(3010) ); // 3 for(;;) { // 4 RWPortal sock = listener(); // 5 RWPortalIStream strm(sock); // 6 RWCString newGreeting; // 7 newGreeting.readLine(strm); sock.sendAtLeast(greeting); // 8 greeting = newGreeting; // 9 } //10 } catch( const RWxmsg& msg ) { cerr << "Error: " << msg.why() << endl; } return 0; }
//1 | As with the client code, the entire server code is wrapped in a try block and all errors are handled in a single catch clause. |
//2 | The string greeting is the salutation provided by the last caller. |
//3 | Here we create an RWSocketListener. A listener waits for connections to arrive on its particular address. In this case, we wait for connections on port 3010 of this host. |
//4 | The server runs forever, handling one connection after another. |
//5 | The RWSocketListener parenthesis operator returns a portal connected to the next waiting incoming connection. This is like answering the phone. If there are no waiting connections (the phone isn't ringing) then this call blocks until a call arrives. |
//6 | Construct a C++ input stream, an istream, connected to the connection that just arrived. An istream provides a higher level data stream abstraction than the RWPortal. We need this higher level to easily read a single line of input. |
//7 | Declare a string, and then read this client's salutation from the input stream we constructed earlier. |
//8 | Send the previous greeting back to the client. |
//9 | Remember what this client told us for next time. |
//10 | When the scope of the for loop ends, the objects declared inside the loop are implicitly destructed by the compiler. This is when the connection gets closed down. |
©Copyright 2000, Rogue Wave Software, Inc.
Contact Rogue Wave about documentation or support issues.