Netutil base protocol implementation #402

Closed
wants to merge 5 commits into
from

Projects

None yet

3 participants

@kachayev
Contributor

If we will use netutil.TCPServer for implementing some functionality, we will have to use inheritance and write duplicated code more and more times... (example of such application you can find here https://gist.github.com/1387470).

The keynote here that there are many situation when we don't want to create server class (inherited from netutil.TCPServer), we just want to use custom handler as wrapper for incoming IOStream. We can easily avoid this problem, code example in docstring to BaseProtocol. Duplicate this example here:

class EchoProtocol(BaseProtocol):
    def _on_connect(self):
        self._wait()

    def _wait(self):
        self.stream.read_unit(b('\n'), self._on_read)

    def _on_read(self, line):
        self.stream.write(line, callback=self._wait)

server = TCPServer(protocol=EchoProtocol)
server.listen(8888)
IOLoop.instance().start() 

It also possible to implement this approach for httpserver.HTTPConnection (request_callback, no_keep_alive and xheaders can be read from server param). But I don't know if it will bring many benefits (only one - standard approach).

@e98cuenc e98cuenc commented on an outdated diff Nov 28, 2011
tornado/netutil.py
@@ -217,6 +225,50 @@ class TCPServer(object):
logging.error("Error in connection callback", exc_info=True)
+class BaseProtocol(object):
+ """Base class for implementing handlers for TCP connections.
+
+ Example of how to use ``BaseProtocol`` for impelementing simple
@e98cuenc
e98cuenc Nov 28, 2011

it should be: "... to implement a simple"

@bdarnell
Member

Closing out this PR; subclassing is the way TCPServer works.

@bdarnell bdarnell closed this Jul 16, 2014
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment