初学tornado,尝试写了一下简易聊天室。
class EchoHandler(tornado.websocket.WebSocketHandler):
users = set()
def check_origin(self, origin):
return True
def open(self):
self.users.add(self)
for u in self.users:
u.write_message('欢迎用户[%s]-[%s]' %(self.request.remote_ip,datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
@tornado.gen.coroutine
def on_message(self, message):
for u in self.users:
u.write_message(u"[%s]-[%s]-说:%s" % (self.request.remote_ip,datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),message))
def on_close(self):
self.users.remove(self)
for u in self.users:
u.write_message(u"[%s]-[%s]-离开了" % (self.request.remote_ip,datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
主要是借着websocket深层理解一下tornado的异步功能,写给以后的自己哈哈
网友评论