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
  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_output_fixed_height(True)
  34. set_title("PyWebIO Chat Room")
  35. put_markdown("""欢迎来到聊天室,你可以和当前所有在线的人聊天\n
  36. 本应用使用不到80行代码实现,源代码[链接](https://github.com/wang0618/PyWebIO/blob/master/demos/chat_room.py)""", lstrip=True)
  37. nickname = await input("请输入你的昵称", required=True,
  38. valid_func=lambda n: '昵称已被使用' if n in online_users or n == '📢' else None)
  39. online_users.add(nickname)
  40. chat_msgs.append(('📢', '`%s`加入聊天室. 当前在线人数 %s' % (nickname, len(online_users))))
  41. put_markdown('`📢`: `%s`加入聊天室. 当前在线人数 %s' % (nickname, len(online_users)))
  42. @defer_call
  43. def on_close():
  44. online_users.remove(nickname)
  45. chat_msgs.append(('📢', '`%s`退出聊天室. 当前在线人数 %s' % (nickname, len(online_users))))
  46. refresh_task = run_async(refresh_msg(nickname))
  47. while True:
  48. data = await input_group('发送消息', [
  49. input(name='msg', help_text='消息内容支持Markdown 语法', required=True),
  50. actions(name='cmd', buttons=['发送', {'label': '退出', 'type': 'cancel'}])
  51. ])
  52. if data is None:
  53. break
  54. put_markdown('`%s`: %s' % (nickname, data['msg']))
  55. chat_msgs.append((nickname, data['msg']))
  56. refresh_task.close()
  57. put_text("你已经退出聊天室")
  58. if __name__ == '__main__':
  59. start_server(main, debug=True, port=8080)