Writing a Server Program That Uses RWSecureSocketPortal
Example 4 is a server program that uses a portal to create a secure socket that waits for requests. Comments are included only for code that is different than Example 3.
This example uses utility functions provided in args.h.
Example 4 – Server program that uses RWSecureSocketPortal
// File:
// examples\secsock\manual\RWSecureSocketPortalSimpleServer.cpp
 
#include <rw/secsock/RWSecureSocketContext.h>
#include <rw/secsock/RWSecureSocketListener.h>
#include <rw/secsock/RWSecureSocketPackageInit.h>
#include <rw/secsock/RWSecureSocketPortal.h>
 
#include <rw/network/RWInetAddr.h>
#include <rw/network/RWWinSockInfo.h>
 
#include <rw/rstream.h>
 
#include <fstream>
#include <iostream>
 
#include "args.h"
#include "secsockexampledefs.h"
 
using std::ifstream;
using std::cout;
using std::cerr;
using std::endl;
 
int main(int argc, char **argv)
{
try {
RWWinSockInfo info; //1
RWSecureSocketPackageInit secsockInit; //2
#if defined(RW_SECSOCK_RNG_NEEDS_SEEDING)
RWSecureSocketPackageInit::seedRNGFromFile(SEED_DATA_FILE);
#endif
int port = parseServerCommandLine(argc, argv);
 
RWSecureSocketContext context; //3
 
ifstream certf(SERVER_CERT_FILE);
RWX509Certificate cert(certf); //4
ifstream keyf(SERVER_PRIVATE_KEY_FILE);
RWPrivateKey key(keyf); //5
context.setIdentity(cert, key); //6
 
RWInetAddr addr(port, "localhost"); //7
RWSecureSocketListener listener(addr, context); //8
 
// Display the port actually bound to
cout << listener.getSocket().getsockname() << endl;
 
char buf[64];
for(volatile bool spin = true; spin ; /* */) {
RWSecureSocketPortal newPortal = listener(); //9
 
buf[newPortal.recv(buf, 63)] = 0; //10
cout << "Received: " << buf << endl; //11
}
}
catch (const RWxmsg& m) {
cerr << m.why() << endl;
return 1;
}
return 0;
}
//1 Initialize Windows Sockets library (does nothing on UNIX).
//2 Initialize the Secure Sockets package.
//3 Create a context instance to hold information related to the SSL connection.
//4 Load the server's certificate.
//5 Load the server's private key.
//6 Associate the certificate and private key with the context.
//7 Create an address instance which will be where the server listens for connections.
//8 Create the listener instance passing the address to bind to and the context which contains the SSL connection information.
//9 The function call operator (operator()) on a listener blocks and waits for a connection to arrive. Upon connection a portal to the newly created socket is returned.
//10 Use the new portal. In this case we call recv() waiting for the client to send some data.
//11 The data sent by the client is printed to standard output.