server.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #!usr/bin/python
  2. import time
  3. import json
  4. import socket
  5. import select
  6. import threading
  7. serversock = None
  8. HOST = '0.0.0.0'
  9. PORT = 6546
  10. SOCKET_TIMEOUT = 5
  11. all_players = {}
  12. class Player:
  13. def __init__(self, socket, name = 'anonymous'):
  14. self.name = name
  15. self.score = 0
  16. self.hand = []
  17. self.socket = socket
  18. def set_hand(self, hand):
  19. self.hand = hand
  20. self.socket.send(bytes(json.dumps(hand), 'utf-8'))
  21. def __del__(self):
  22. self.socket.close()
  23. def broadcast(client_list, data):
  24. for c in client_list:
  25. c.send(data)
  26. def listen(host, port):
  27. serversock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  28. serversock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  29. serversock.bind((host, port))
  30. serversock.listen(10)
  31. while True:
  32. print('waiting in select')
  33. #all_socks = all_connections + [serversock]
  34. all_socks = list(all_players.keys()) + [serversock]
  35. readable, writable, exceptional = select.select(
  36. all_socks, [], all_socks)
  37. if len(exceptional) >= 1:
  38. print('exceptional! %s' % (client_address,))
  39. continue
  40. if len(readable) >= 1:
  41. print('len >= 1')
  42. if serversock in readable:
  43. print('serversock in')
  44. current_connection, client_address = serversock.accept()
  45. new_player = Player(current_connection)
  46. new_player.set_hand([1,2,420,69])
  47. all_players[current_connection] = new_player
  48. print('%s connected' % (client_address,))
  49. else:
  50. print('broadcast')
  51. client = readable[0]
  52. data = client.recv(1024)
  53. if len(data) <= 0:
  54. print('client - hangup')
  55. del all_players[client]
  56. else:
  57. broadcast(list(all_players.keys()), data)
  58. continue
  59. if __name__ == '__main__':
  60. try:
  61. listen(HOST, PORT)
  62. except KeyboardInterrupt:
  63. print('interrupt - exiting')
  64. print('n_connections: %d' % (len(all_players),))
  65. for client in all_players:
  66. del client
  67. time.sleep(1)
  68. exit(9)