Skip to content

Instantly share code, notes, and snippets.

@mrjoes
Created March 9, 2012 19:55
Show Gist options
  • Save mrjoes/2008335 to your computer and use it in GitHub Desktop.
Save mrjoes/2008335 to your computer and use it in GitHub Desktop.
# -*- 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 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)]# + ChatRouter.urls
)
# 3. Make Tornado app listen on port 8080
app.listen(8080)
app2 = tornado.web.Application(ChatRouter.urls)
app2.listen(8081)
# 4. Start IOLoop
tornado.ioloop.IOLoop.instance().start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment