The classes presented here provide an easy way to develop scalable socket servers using IO completion and thread pooling in such a way that the user of the classes need not concern themselves with these low level issues. To create your own server simply derive from CSocketServer to create your listening socket, handle connection establishment and any of the other notifications that you require. Then derive from the WorkerThread class to provide the byte stream chunking and business logic. Running your server is as simple as this:
CSocketServer server( "+OK POP3 server ready\r\n", INADDR_ANY, // address to listen on 5001, // port to listen on 10, // max number of sockets to keep in the pool 10, // max number of buffers to keep in the pool 1024); // buffer size server.Start(); server.StartAcceptingConnections();
Your code can then do whatever it likes and the socket server runs on its own threads. When you are finished, simply call:
server.WaitForShutdownToComplete();
And the socket server will shutdown.
In the next article we address the issue of moving the business logic out of the IO thread pool and into a thread pool of its own so that long operations don't block the IO threads.
DownloadThe source was built using Visual Studio 6.0 SP5 and Visual Studio .Net. You need to have a version of the Microsoft Platform SDK installed
All of the zip files mentioned can be found in the single zip file attached to this article.
- SocketServer1.zip - yet another echo server
- SocketServer2.zip - a packet based echo server
- SocketServer3.zip - a dummy POP3 server
- ServerShutdown.zip - an off switch for the servers
- 21st May 2002 - Initial revision posted on www.jetbyte.com.
- 27th May 2002 - Added pause/resume functionality to all servers and the server shutdown program. Use CSocket to protect from resource leaks when creating the listening socket. Refactored the Socket and CIOBuffer classes so that common list management code is now in CNodeList and common user data code is now in COpaqueUserData.
- 29th May 2002 - Linting and general code cleaning
- 18th June 2002 - Removed call to ReuseAddress() during the creation of the listening socket as it not required - Thanks to Alun Jones for pointing this out to me.
Comments