chat_room.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. """
  2. 聊天室
  3. ^^^^^^^^^^^
  4. 和当前所有在线的人聊天
  5. :demo_host:`Demo地址 </?pywebio_api=chat_room>` `源码 <https://github.com/wang0618/PyWebIO/blob/master/demos/chat_room.py>`_
  6. * 使用基于协程的会话
  7. * 使用 `run_async() <pywebio.session.run_async>` 启动后台协程
  8. """
  9. import asyncio
  10. from pywebio import start_server, run_async
  11. from pywebio.input import *
  12. from pywebio.output import *
  13. from pywebio.session import defer_call, set_env
  14. # 最大消息记录保存
  15. MAX_MESSAGES_CNT = 10 ** 4
  16. chat_msgs = [] # 聊天记录 (name, msg)
  17. online_users = set() # 在线用户
  18. async def refresh_msg(my_name):
  19. """刷新聊天消息"""
  20. global chat_msgs
  21. last_idx = len(chat_msgs)
  22. while True:
  23. await asyncio.sleep(0.5)
  24. for m in chat_msgs[last_idx:]:
  25. if m[0] != my_name: # 仅刷新其他人的新信息
  26. put_markdown('`%s`: %s' % m)
  27. # 清理聊天记录
  28. if len(chat_msgs) > MAX_MESSAGES_CNT:
  29. chat_msgs = chat_msgs[len(chat_msgs) // 2:]
  30. last_idx = len(chat_msgs)
  31. async def main():
  32. global chat_msgs
  33. set_env(title="PyWebIO Chat Room", output_fixed_height=True)
  34. put_markdown("""欢迎来到聊天室,你可以和当前所有在线的人聊天\n
  35. 本应用使用不到80行代码实现,源代码[链接](https://github.com/wang0618/PyWebIO/blob/master/demos/chat_room.py)""", lstrip=True)
  36. nickname = await input("请输入你的昵称", required=True,
  37. validate=lambda n: '昵称已被使用' if n in online_users or n == '📢' else None)
  38. online_users.add(nickname)
  39. chat_msgs.append(('📢', '`%s`加入聊天室. 当前在线人数 %s' % (nickname, len(online_users))))
  40. put_markdown('`📢`: `%s`加入聊天室. 当前在线人数 %s' % (nickname, len(online_users)))
  41. @defer_call
  42. def on_close():
  43. online_users.remove(nickname)
  44. chat_msgs.append(('📢', '`%s`退出聊天室. 当前在线人数 %s' % (nickname, len(online_users))))
  45. refresh_task = run_async(refresh_msg(nickname))
  46. while True:
  47. data = await input_group('发送消息', [
  48. input(name='msg', help_text='消息内容支持Markdown 语法', required=True),
  49. actions(name='cmd', buttons=['发送', {'label': '退出', 'type': 'cancel'}])
  50. ])
  51. if data is None:
  52. break
  53. put_markdown('`%s`: %s' % (nickname, data['msg']))
  54. chat_msgs.append((nickname, data['msg']))
  55. refresh_task.close()
  56. put_text("你已经退出聊天室")
  57. if __name__ == '__main__':
  58. start_server(main, debug=True, port=8080)