選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

123 行
3.7KB

  1. import asyncio
  2. import collections
  3. import datetime
  4. import http
  5. import json
  6. from functools import partial
  7. from pathlib import Path
  8. import websockets
  9. rooms = collections.defaultdict(dict)
  10. class PicoProtocol(websockets.WebSocketServerProtocol):
  11. def serve_file(self, path):
  12. document = Path(__file__, '..', Path(path).name).resolve()
  13. if not document.is_file():
  14. document = Path(__file__, '..', 'pico.html').resolve()
  15. content_type = 'text/html; charset=utf-8'
  16. elif path.endswith('.js'):
  17. content_type = 'application/javascript; charset=utf-8'
  18. elif path.endswith('.css'):
  19. content_type = 'text/css; charset=utf-8'
  20. else:
  21. content_type = 'text/plain; charset=utf-8'
  22. return (
  23. http.HTTPStatus.OK,
  24. [('Content-Type', content_type)],
  25. document.read_bytes(),
  26. )
  27. async def process_request(self, path, request_headers):
  28. if request_headers.get('Upgrade') != 'websocket':
  29. return self.serve_file(path)
  30. return await super().process_request(path, request_headers)
  31. async def send_json_many(targets, **data):
  32. for websocket in list(targets):
  33. await send_json(websocket, **data)
  34. async def send_json(websocket, **data):
  35. try:
  36. await websocket.send(json.dumps(data))
  37. except websockets.exceptions.ConnectionClosed:
  38. pass
  39. async def recv_json(websocket):
  40. try:
  41. return json.loads(await websocket.recv())
  42. except websockets.exceptions.ConnectionClosed:
  43. return {'kind': 'logout'}
  44. except json.decoder.JSONDecodeError:
  45. return {}
  46. async def core(ws, path, server_name):
  47. room = rooms[path]
  48. usernames = room.keys()
  49. sockets = room.values()
  50. username = None
  51. while True:
  52. data = await recv_json(ws)
  53. ts = datetime.datetime.now().isoformat() + 'Z'
  54. emit = partial(send_json_many, kind=data['kind'], value=data.get('value'), ts=ts)
  55. broadcast = partial(emit, targets=sockets)
  56. reply = partial(emit, targets=[ws])
  57. error = partial(reply, kind='error')
  58. if 'kind' not in data:
  59. await error(value='Message without kind is invalid')
  60. elif data['kind'] == 'login':
  61. username = data['value']
  62. if not username:
  63. await error(value='Username not allowed')
  64. break
  65. if username in usernames:
  66. await error(value='Username taken')
  67. break
  68. others = list(sockets)
  69. room[username] = ws
  70. online = list(usernames)
  71. await reply(online=online)
  72. await broadcast(kind='post', value=f'{username} joined', online=online, targets=others)
  73. await reply(kind='post', value=f'Welcome to {path}')
  74. elif username not in room:
  75. await error(value='Login required')
  76. break
  77. elif data['kind'] == 'logout':
  78. del room[username]
  79. online = list(usernames)
  80. await broadcast(kind='post', value=f'{username} left', online=online)
  81. break
  82. else:
  83. if 'target' in data:
  84. targets = {v for k, v in room.items() if k in {username, data['target']}}
  85. await broadcast(source=username, targets=targets)
  86. else:
  87. await broadcast(source=username)
  88. async def start_server(host, port, server_name):
  89. bound_core = partial(core, server_name=server_name)
  90. return await websockets.serve(bound_core, host, port, create_protocol=PicoProtocol)
  91. if __name__ == '__main__':
  92. host, port = 'localhost', 9753
  93. loop = asyncio.get_event_loop()
  94. loop.run_until_complete(start_server(host, port, 'PicoChat'))
  95. print(f'Running on {host}:{port}')
  96. loop.run_forever()