-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
64 lines (52 loc) · 2.13 KB
/
Copy pathserver.py
File metadata and controls
64 lines (52 loc) · 2.13 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
from tornado import httpserver
import tornado.websocket
import tornado.ioloop
import tornado.web
clients = []
userid = 0
class WSHandler(tornado.websocket.WebSocketHandler):
#Called when attempt is made for connection from client
def open(self):
obj = SessionManagement()
obj.createsession(self)#storing web socket object for further communication with client
#Called when client sends message
def on_message(self, message):
print 'message received %s' % userid
#Called when user refreshes or closes the page
def on_close(self):
obj = SessionManagement()
obj.deletesession(self)#deleting web socket object
print clients
class SessionManagement():
#Create session and stores into array
def createsession(self, obj):
userid = obj.get_argument("userid")
componentid = obj.get_argument("compid")
clients.append({"wsobj":obj, "userid":userid, "compid":componentid})
#Delete session from array when client refreshes the page or closes the page
def deletesession(self, obj):
for temp in clients:
if (obj==temp['wsobj']):
clients.remove(temp)
class PushToUser(tornado.web.RequestHandler):
def get(self):
userid = self.get_argument('userid')
compid = self.get_argument('compid')
message = self.get_argument('message')
for temp in clients:
if (temp['userid'] == userid and temp['compid'] == compid):
temp['wsobj'].write_message(message)
class PushToAll(tornado.web.RequestHandler):
def get(self):
message=self.get_argument('message')
for temp in clients:
temp['wsobj'].write_message(message)
application = tornado.web.Application([
(r'/ws', WSHandler),
(r'/push', PushToUser), #Ex. /push?userid=123&compid=123&message=hello
(r'/pushtoall', PushToAll), #Ex. /pushtoall?message="hello"
])
if __name__ == "__main__":
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(8888)
tornado.ioloop.IOLoop.instance().start()