-
Notifications
You must be signed in to change notification settings - Fork 0
/
run.py
53 lines (38 loc) · 1.48 KB
/
run.py
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
from twisted.internet import reactor
from twisted.web.server import Site
from twisted.web.static import File
from autobahn.twisted.websocket import WebSocketServerFactory, WebSocketServerProtocol, listenWS
from control import toggle, setSwitchStatus
from config import ports
class BroadcastServerProtocol(WebSocketServerProtocol):
def onOpen(self):
self.factory.register(self)
setSwitchStatus()
def onMessage(self, payload, isBinary):
message = payload.decode('utf8')
toggle()
self.factory.broadcast(message)
def connectionLost(self, reason):
WebSocketServerProtocol.connectionLost(self, reason)
self.factory.unregister(self)
class BroadcastServerFactory(WebSocketServerFactory):
def __init__(self, url, debug=False, debugCodePaths=False):
WebSocketServerFactory.__init__(self, url)
self.clients = []
def register(self, client):
if client not in self.clients:
self.clients.append(client)
def unregister(self, client):
if client in self.clients:
self.clients.remove(client)
def broadcast(self, msg):
for client in self.clients:
client.sendMessage(msg.encode('utf8'))
ServerFactory = BroadcastServerFactory
factory = ServerFactory("ws://localhost:%s" % ports["ws_server"])
factory.protocol = BroadcastServerProtocol
listenWS(factory)
web_root = File("web")
web = Site(web_root)
reactor.listenTCP(ports["static_server"], web)
reactor.run()