-
Notifications
You must be signed in to change notification settings - Fork 0
/
net_server.py
41 lines (26 loc) · 936 Bytes
/
net_server.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
import tornado.ioloop
import tornado.web
import tornado.websocket
import json
import os
clients = {}
class WebSocketHandler(tornado.websocket.WebSocketHandler):
def check_origin(self, origin):
return True
def open(self, *args):
self.app = args[0]
clients[self.app] = clients.get(self.app) or []
clients[self.app].append(self)
print "Added client for \"%s\" app: %s" % (self.app, self.request.remote_ip)
def on_message(self, message):
print "%s (%s) says: %s" % (self.app, self.request.remote_ip, message)
obj = json.loads(message)
for client in clients[self.app]:
if client != self or obj.get("echo"):
client.write_message(json.dumps(obj.get("data")))
def on_close(self):
clients[self.app].remove(self)
app = tornado.web.Application([(r'/(.*)', WebSocketHandler)])
port = int(os.environ.get("PORT", 9090))
app.listen(port)
tornado.ioloop.IOLoop.instance().start()