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;
}
//1 Initializes the winsock library if appropriate (Windows platform only)
//2 Creates an address object, which represents the IP address and port number that this server will be waiting for client connections on.
//3 Binds the server side socket to the address constructed in the first step.
//4 Waits for an incoming connection, assigning that connection to conn for later use.
//5 Constructs a time object, which represents the current date and time.
//6 Formats the time object as a string so we can easily send it to the client.
//7 Send the response.
//8 Close the connection to the client and wait for further client connections.
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);