Reputation: 816
I want to build a server that will be able to handle TCP, HTTP and Websockets protocols (not concurrently) and be able to work the same no matter what protocol it will use at runtime.
Basically I don't what to treat each type of request differently, but somehow to make a general request object and a general response object.
Messages received through TCP and Websockets will have the structure of an http request.
All requests/messages will be REST-like.
What architectural design should I use in order to not duplicate the routing/processing for each protocol?
Upvotes: 2
Views: 132
Reputation: 475
Any TCP Server can be also a HTTP server. If you check https://docs.python.org/2/library/socketserver.html and https://docs.python.org/2/library/basehttpserver.html you will see HTTPServer extends TCPServer.
After the request is coming in your TCP server just find out if it is a "HTTP request" (this is the difficult part) and forward it to an HTTP router (almost any decent MVC framework in any language has one).
If we consider TCP request and HTTP request are similar, you could transform the TCP request in an HTTP request and forward it to the same router. Anyway, this approach can slow down all the processing.
Also, if you already have only TCP clients & server then I would keep them separately due the fact the HTTP introduces some overhead. So, another approach would be to keep the server and the router separately per protocol and use only the business logic classes (Models) as a common layer.
TCP Server --> FC -->TCP Router --> TCPController(Controller) --> TCP Response
|
\/
Model
/\
|
HTTP Server --> FC --> HTTP Router --> HTTPController(Controller) --> HTTP Response
*FC = Front Controller
Using this approach, you can replace the HTTP Server any time with another one and this can bring multiple advantages: use a well known web server (like nginx) or a custom one written by yourself in different languages.
Upvotes: 1