Exercise: Abstract TCP server

Until now you programmed quite a few TCP server applications.

They all share the same general structure:

  1. Make a TcpListener object using host IP + port number
  2. Start the server
  3. Enter the server loop
  4. Wait for incoming client ... AcceptTcpClient()
  5. Give service to the client ... DoIt()
  6. Have a Stop() method to stop the client
  7. Do some Tracing on the way (later when you learned about Tracing)

In this exercises you must put all this general stuff in an separate class TcpServer.

Abstract class

Make another Visual Studio solution.

In this solution make an abstract class TcpServer.

This class is abstract, because the DoIt(...) method is abstract

Servers, like Echo, etc, then extends the TcpServer class and implement the DoIt(...) method.

Essentially you have used the Template Method design pattern.
In this case Start() is the template method: Start() is implemented in the TcpServer class, but it calls a method, DoIt(), which is abstract.

Template Method design pattern is often used in frameworks where the users of the framework can add new behavior to the existing classes by making sub-classes and (re-)defining methods from the base classes. You can consider TcpServer a very small framework!

Testing

To test the abstract class you must first implement the abstract class: Make an EchoServer which extends TcpServer.

Interface

All important classes should have an interface and other classes should refer to the class through this interface.

Extract an interface from the TcpServer class. The name of the interface must be ITcpServer.

Visual Studio can help you extract the interface.

Use the interface in the test, etc.