這幾天在看Tornado的source code,有一些體會,自己動手寫了一個基於tornado tcpserver的echoserver

#!/usr/bin/env python

from tornado.netutil import TCPServer
from tornado.ioloop  import IOLoop

class ECHOConnection(object):
    def __init__(self, stream):
        self._stream = stream
        self.read()
    
    def read(self):
        self._stream.read_until('\r\n', self.echo_callback)
    
    def echo_callback(self, data):
        print "data:", data
        self._stream.write(data)
        self.read()

class ECHOServer(TCPServer):
    def handle_stream(self, stream, address):
        print "echo connecting..."
        ECHOConnection(stream)

if __name__ == '__main__':
    print "begin..."
    server = ECHOServer()
    server.listen(8000)
    IOLoop.instance().start()    


Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐