Until now you programmed quite a few TCP server applications.
They all share the same general structure:
TcpListener
object using host IP + port numberAcceptTcpClient()
DoIt()
Stop()
method to stop the clientIn this exercises you must put all this general stuff in an separate class TcpServer
.
Make another Visual Studio solution.
In this solution make an abstract class TcpServer
.
This class is abstract, because the DoIt(...)
method is abstract
protected abstract void DoIt(TcpClient client);
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!
To test the abstract class you must first implement the abstract class: Make an EchoServer which extends TcpServer.
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.