-
Notifications
You must be signed in to change notification settings - Fork 0
/
chat.py
60 lines (43 loc) · 1.64 KB
/
chat.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
54
55
56
57
58
59
60
# -*- coding: utf-8 -*-
"""
Simple sockjs-tornado chat application. By default will listen on port 8080.
"""
import tornado.ioloop
import tornado.web
import sockjs.tornado
class IndexHandler(tornado.web.RequestHandler):
"""Regular HTTP handler to serve the chatroom page"""
def get(self):
self.render('index.html')
class ReqHandler(tornado.web.RequestHandler):
def post(self):
[el.send("HELLO") for el in ChatConnection.participants]
class ChatConnection(sockjs.tornado.SockJSConnection):
"""Chat connection implementation"""
# Class level variable
participants = set()
def on_open(self, info):
# Send that someone joined
self.broadcast(self.participants, "Someone joined.")
# Add client to the clients list
self.participants.add(self)
def on_message(self, message):
# Broadcast message
self.broadcast(self.participants, message)
def on_close(self):
# Remove client from the clients list and broadcast leave message
self.participants.remove(self)
self.broadcast(self.participants, "Someone left.")
if __name__ == "__main__":
import logging
logging.getLogger().setLevel(logging.DEBUG)
# 1. Create chat router
ChatRouter = sockjs.tornado.SockJSRouter(ChatConnection, '/chat')
# 2. Create Tornado application
app = tornado.web.Application([(r"/", IndexHandler),
(r"/api", ReqHandler)] + ChatRouter.urls
)
# 3. Make Tornado app listen on port 8080
app.listen(8080)
# 4. Start IOLoop
tornado.ioloop.IOLoop.instance().start()