RWSocketListener
Class
RWSocketListener is another commonly used class of the Essential Networking Module. This class makes it easy to create server applications by encapsulating the work needed to listen for and accept incoming connections. An
RWSocketListener creates a listening socket, which can wait for incoming connections. Its overloaded
operator() waits for a connection and returns it as a new
RWSocketPortal. To use
RWSocketListener, just create one with the port you'd like to listen on as shown:
RWSocketListener listener(RWInetAddr(1234)); // 1
while(1) {
RWSocketPortal socketPortal = listener(); // 2
serviceClient(socketPortal); // 3
}
On
//1, we create a new
RWSocketListener, telling it to listen for new connections on port
1234. This sets up a queue for incoming connections, but does not cause the program to wait for a new connection. On
//2 we wait for the new connection by invoking the listener as if it were a function, made syntactically possible by the
RWSocketListener overloaded
operator().
Once a client connects to our port
1234, an
RWSocketPortal connected to the new client is returned on
//2. On
//3, the client is serviced in our imaginary
serviceClient() function that we created in
RWPortal as a Base. In a real server,
serviceClient() might hand the new connection to a separate thread to be serviced. Since local objects declared inside a
while loop are destroyed and recreated on each loop iteration, the connection to each client is automatically closed.