-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathserver.py
More file actions
89 lines (75 loc) · 2.2 KB
/
server.py
File metadata and controls
89 lines (75 loc) · 2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import cherrypy
from cherrypy.lib.static import serve_file
import os
import sys
import webbrowser
import threading
import time
import socket
import json
from client import addClient, loadClients, clearClients, clientsList, removeClient
from transmitJSON import sendJSON, recvJSON
def getRootDir():
return os.path.dirname(os.path.abspath(sys.argv[0]))
def manageClient(client, addr):
data = recvJSON(client)
data['ip']=addr[0]
try:
addClient(data)
sendJSON(client, {'ok': True})
except ValueError as e:
sendJSON(client, {'ok': False, 'error': str(e)})
finally:
client.close()
def subscribeHandler():
s = socket.socket()
s.settimeout(0.5)
s.bind(('0.0.0.0', 3001))
s.listen()
print('listen for subscription on port', 3001)
while running:
try:
client, addr = s.accept()
manageClient(client, addr)
except socket.timeout:
pass
print('no more listen for subscription')
def startBrowser():
time.sleep(2)
webbrowser.open('http://localhost:3000')
print('browser started !')
class Server:
@cherrypy.expose(['game.js'])
def game(self):
cherrypy.response.headers['Content-Type'] = 'application/javascript'
return gameJS
@cherrypy.expose
@cherrypy.tools.json_out()
def clients(self):
return clientsList()
@cherrypy.expose
@cherrypy.tools.json_out()
@cherrypy.tools.json_in()
def remove(self):
data = cherrypy.request.json
removeClient(data['name'])
if __name__ == '__main__':
if len(sys.argv) > 1:
game = sys.argv[1]
else:
game = 'matches'
with open(os.path.join(getRootDir(),f'public/games/{game}.js')) as file:
gameJS = file.read().encode('utf8')
running = True
threading.Thread(target=startBrowser).start()
thread = threading.Thread(target=subscribeHandler)
thread.start()
def stop():
print('STOPPING subscription handler...')
global running
running = False
thread.join()
print('subscription handler stopped')
loadClients()
cherrypy.engine.subscribe('stop', stop)
cherrypy.quickstart(Server(), '', 'server.conf')