chat_room.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. from tornado import gen
  2. from tornado.ioloop import IOLoop
  3. from tornado import websocket
  4. import json
  5. from wsrepl.ioloop import start_ioloop
  6. from wsrepl.interact import *
  7. from tornado.gen import sleep
  8. chat_msgs = [] # 聊天记录 (name, msg)
  9. def refresh_msg(my_name):
  10. last_idx = len(chat_msgs)
  11. while True:
  12. yield sleep(0.5)
  13. for m in chat_msgs[last_idx:]:
  14. if m[0] != my_name: # 仅刷新其他人的新信息
  15. text_print('%s:%s' % m)
  16. last_idx = len(chat_msgs)
  17. # 业务逻辑 协程
  18. def main():
  19. """
  20. 有返回值的交互函数需要yield from
  21. :return:
  22. """
  23. set_title("Chat Room")
  24. text_print("欢迎来到聊天室,你可以和当前所有在线的人聊天")
  25. nickname = yield from input("请输入你的昵称", required=True)
  26. chat_msgs.append(('*系统*', '%s加入房间' % nickname))
  27. text_print("*系统*: %s加入房间" % nickname)
  28. run_async(refresh_msg(nickname))
  29. while True:
  30. data = yield from input_group('输入消息', [
  31. input('', name='msg'),
  32. actions('', name='cmd', buttons=['发送', '退出'])
  33. ])
  34. if data['cmd'] == '退出':
  35. break
  36. text_print('%s:%s' % (nickname, data['msg']))
  37. chat_msgs.append((nickname, data['msg']))
  38. text_print("你已经退出聊天室")
  39. start_ioloop(main)