chat_room.py 1.4 KB

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