diff --git a/2022/01/tornado_demo1/.gitignore b/2022/01/tornado_demo1/.gitignore new file mode 100644 index 0000000..be2dd1b --- /dev/null +++ b/2022/01/tornado_demo1/.gitignore @@ -0,0 +1,3 @@ +.idea +*.iml +env diff --git a/2022/01/tornado_demo1/client.py b/2022/01/tornado_demo1/client.py new file mode 100644 index 0000000..e72e58c --- /dev/null +++ b/2022/01/tornado_demo1/client.py @@ -0,0 +1,45 @@ +from tornado.ioloop import IOLoop, PeriodicCallback +from tornado import gen +from tornado.websocket import websocket_connect + + +class Client(object): + def __init__(self, url, timeout): + self.url = url + self.timeout = timeout + self.ioloop = IOLoop.instance() + self.ws = None + self.connect() + PeriodicCallback(self.keep_alive, 20000).start() + self.ioloop.start() + + @gen.coroutine + def connect(self): + print("trying to connect") + try: + self.ws = yield websocket_connect(self.url) + print("connected") + self.run() + except Exception: + print("connection error") + + @gen.coroutine + def run(self): + while True: + msg = yield self.ws.read_message() + if msg is None: + print("connection closed") + self.ws = None + break + else: + print("Got a message: " + msg) + + def keep_alive(self): + if self.ws is None: + self.connect() + else: + self.ws.write_message("keep alive") + + +if __name__ == "__main__": + client = Client("ws://localhost:8888/socket", 5) diff --git a/2022/01/tornado_demo1/requirements.txt b/2022/01/tornado_demo1/requirements.txt new file mode 100644 index 0000000..c3368df --- /dev/null +++ b/2022/01/tornado_demo1/requirements.txt @@ -0,0 +1 @@ +tornado diff --git a/2022/01/tornado_demo1/server.py b/2022/01/tornado_demo1/server.py new file mode 100644 index 0000000..274bbf1 --- /dev/null +++ b/2022/01/tornado_demo1/server.py @@ -0,0 +1,26 @@ +import tornado.ioloop +import tornado.web +import tornado.websocket + +class MainHandler(tornado.web.RequestHandler): + def get(self): + self.write("Hello, world") + +class WebsocketHandler(tornado.websocket.WebSocketHandler): + def open(self): + print("Opened...") + + def on_message(self, message): + print("Got a message: " + message) + self.write_message(u"You wrote: {0}".format(message)) + + def on_close(self): + print("Closed...") + +if __name__ == "__main__": + application = tornado.web.Application([ + (r"/", MainHandler), + (r"/socket", WebsocketHandler), + ]) + application.listen(8888) + tornado.ioloop.IOLoop.current().start()