Skip to content

Instantly share code, notes, and snippets.

@binux
Created Dec 23, 2014
Embed
What would you like to do?
import threading
import tornado
import tornado.httpserver
import tornado.websocket
wss = []
class WSHandler(tornado.websocket.WebSocketHandler):
def check_origin(self, origin):
return True
def open(self):
print ('New connection established.')
if self not in wss:
wss.append(self)
def on_message(self, message):
print ('Received message: %s' % message)
write_data(message)
def on_close(self):
print ('Connection closed.')
if self in wss:
wss.remove(self)
class Application(tornado.web.Application):
def __init__(self):
settings = dict(
debug = True,
)
super(Application, self).__init__([ (".*", WSHandler), ], **settings)
application = Application()
def write_data(message):
for ws in wss:
print ("Sending: %s" % message)
ws.write_message(message);
class ServerThread(threading.Thread):
def run(self):
print ("Starting server.")
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(4044)
main_loop = tornado.ioloop.IOLoop.instance()
main_loop.start()
def send_data(self, message):
write_data(message);
server_thread = ServerThread()
server_thread.start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment