A Simple Synchronous Server
The primary job of a server is to accept client connections. This can be done through the use of the Berkeley Socket Adapter.
Example 16 shows a simple daytime server:
Example 16 – Daytime Server
#include <rw/tools/datetime.h>
#include <rw/cstring.h>
#include <rw/network/RWSocket.h>
#include <rw/network/RWInetAddr.h>
#include <rw/network/RWWinSockInfo.h>
int main(void)
{
RWWinSockInfo winsock; // 1
RWInetAddr addr(1025); // 2
RWSocket sock;
sock.listen(addr); // 3
do {
RWSocket conn = sock.accept(); // 4
RWDateTime now = RWDateTime::now(); // 5
RWCString response = now.asString(); // 6
conn.sendAtLeast(response); // 7
conn.close(); // 8
} while(1);
sock.close();
return 0;
}
Example 16 could be further extended to provide some exception handling. Placing a simple
try/
catch inside the loop allows for communication errors to be easily handled, as illustrated below:
do {
RWSocket conn = sock.accept();
RWDateTime now = RWDateTime::now();
RWCString response = now.asString();
try {
conn.sendAtLeast(response);
} catch(const RWxmsg& m) {
cout << "Exception: " << m.why() << endl;
}
conn.close();
} while(1);